我創建了一個很棒的代碼,考慮到背包的最大允許重量,通過重復列舉從串列中回傳物品,總結它們的價格和重量,并給出結果。目前,我面臨的問題是,當最大權重變大(例如 80)時,代碼根本無法運行。我真的不明白這是否是無限回圈或優化的問題,所以我很感激你的幫助!
backpack_max = int(input('Backpack limit: '))
item_list = ['Rune', 'Arrows', 'Rock', 'Sword']
item_weight = [2, 4, 5, 10]
item_price = [20, 4, 1, 15]
backpack_fin_items = []
total_weight = 0
total_price = 0
count = 0
while total_weight min(item_weight) < backpack_max:
for item, price in zip(item_list, item_price):
if total_weight item_weight[count] <= backpack_max:
total_weight = item_weight[count]
backpack_fin_items.append(item.lower())
total_price = price
count = 1
count %= len(item_list)
joint = ', '.join(backpack_fin_items)
print (f'You are packed with loot! \n\nContent: {joint}\n\nTotal weight: {total_weight}/{backpack_max} kg\nTotal price: {total_price} coins\n\nHave a nice adventure, warrior!')
uj5u.com熱心網友回復:
不是你的物品太多,而是你陷入了無法在背包中添加任何物品的狀態。要除錯這樣的小程式,一件有用的事情是print在代碼中執行您不期望的事情的部分中添加 a。
while total_weight min(item_weight) < backpack_max:
print(total_weight, backpack_fin_items)
# ...
在無限回圈中列印:
74 ['rune', 'arrows', 'rock', 'sword', 'rune', 'arrows', 'rock', 'sword', 'rune', 'arrows', 'rock', 'sword', 'rune', 'arrows', 'rock']
74 ['rune', 'arrows', 'rock', 'sword', 'rune', 'arrows', 'rock', 'sword', 'rune', 'arrows', 'rock', 'sword', 'rune', 'arrows', 'rock']
這不直觀,因為看起來我們應該能夠添加權重為 2 的專案。
更仔細地查看代碼:
for item, price in zip(item_list, item_price):
if total_weight item_weight[count] <= backpack_max:
我懷疑問題出在item_weight[count]- 我不清楚這將如何讓你獲得與 相關的重量item,或者count應該做什么。
如果我只是將權重添加到您的zip運算式中并洗掉所有參考的行,count否則它可以正常作業:
for item, price, weight in zip(item_list, item_price, item_weight):
if total_weight weight <= backpack_max:
total_weight = weight
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/451797.html
