我想根據在以前的購物行程中檢查的訂單商品對購物清單進行排序。例如,我去商店購買蘋果、香蕉和雞蛋。
接下來我去商店買鱷梨、西紅柿和蘋果。對于我的下一次旅行,該應用程式在 Eggs fe 之前對 Avocados、Tomatos 和 Apples 進行排序
我發現這篇文章談論拓撲排序:如何根據先前的揀貨順序對購物清單進行排序?.
但是我不確定這應該如何作業,因為理論上我可以有回圈(理論上,用戶可以先檢查蘋果,然后再檢查香蕉,下次香蕉在蘋果之前檢查)。
你能指導我如何解決這個問題嗎?
親切的問候
uj5u.com熱心網友回復:
我假設:
- 過去的專案訂購應指導訂購當前訂單。
- 任何新專案出現在歷史訂購的任何專案之后。
- 更早的訂單應該比最近的訂單影響更小。
我的想法是根據以下條件為過去訂單中看到的商品分配權重:
- 他們在歷史秩序中的地位。
- 那個奧丁是多少歲了。
權重可能需要調整,但是,使用您鏈接到的其他問題的資料,下面的 Python 代碼確實會根據歷史排序創建排序:
from collections import defaultdict
shop = [['Toothpaste', 'Bread', 'Meat', 'Vegetables', 'Milk', 'Ice cream'], # last
['CDs', 'Bread', 'Fruit', 'Vegetables', 'Juice', 'Sugar', 'Chocolates'], # last-but-1
['Meat', 'Juice', 'Milk', 'Sugar']] # last-but-2
def weight_from_index(idx: int) -> float | int:
"Items to the left are of LOwer wt and will sort first."
return idx 1
def historic_multiplier(idy: int) -> float:
"Older rows have larger multipliers and so are of lower overall weight."
return (idy 1)**1
def shopping_weights(history: list[list[str]]) -> dict[str, int | float]:
"Weight for items from historic shops."
item2weight = defaultdict(float)
for y, hist in enumerate(history):
for x, item in enumerate(hist):
item2weight[item] = historic_multiplier(y) * weight_from_index(x)
return dict(item2weight)
def order_items(items: list[str], weights) -> list[str]:
wts = weights.copy()
new_items = set(items) - set(wts)
# New items last, but in given order otherwise
max_wt = max(wts.values())
for itm in new_items:
wts[itm] = max_wt 1 items.index(itm)
return sorted(items, key = lambda i: wts[i])
item_weights = shopping_weights(shop)
new_shop = ['Curry', 'Vegetables', 'Eggs', 'Milk', 'CDs', 'Meat']
new_order = order_items(new_shop, item_weights)
print(new_order)
# ['CDs', 'Meat', 'Vegetables', 'Milk', 'Curry', 'Eggs']
# Update the historic item orders
shop.insert(0, new_order)
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/492032.html
上一篇:這是已知的森林搜索演算法嗎?如果是,它的名字是什么?
下一篇:分而治之與回溯
