0
我想在python中實現貪婪揹包算法給定下面的數據集。輸出應該是列表的列表,它遵守限制集。在例如與輸出下面的數據集應該是:Python - 貪婪揹包與詞典輸入
out = [[C, B, D, A], [Z, F, E]]
代碼:
data = {
'A': 5,
'B': 10,
'C': 11,
'D': 7,
'E': 2,
'Z': 4,
'F': 3
}
def greedy_algo(mystuff, limit=30):
# Copy the dictionary to work on duplicate
copy_stuff = dict(mystuff)
# Initialize an output list
outlist = []
def keywithmaxval(d):
""" a) create a list of the dict's keys and values;
b) return the key with the max value"""
v=list(d.values())
k=list(d.keys())
return k[v.index(max(v))]
def greedy_grab(mydict):
result = []
total = 0
while total <= limit:
maxkey=keywithmaxval(mydict)
result.append(maxkey)
total += mydict[maxkey]
del mydict[maxkey]
return result
def update_dict(mydict, mylist):
for i in mylist:
del mydict[i]
return mydict
while len(copy_stuff) > 0:
outlist.append(greedy_grab(copy_stuff)
return outlist
print (greedy_algo(data, limit=30))
我米運行到與max函數的問題,這是我的輸出:
['C']
['C', 'B']
['C', 'B', 'D']
['C', 'B', 'D', 'A']
['Z']
['Z', 'F']
['Z', 'F', 'E']
Traceback (most recent call last):
File "gre.py", line 72, in <module>
greedy_algo(data, limit=30)
File "gre.py", line 63, in greedy_algo
outlist.append(greedy_grab(copy_stuff))
File "gre.py", line 40, in greedy_grab
maxkey=keywithmaxval(mydict)
File "gre.py", line 28, in keywithmaxval
return k[v.index(max(v))]
ValueError: max() arg is an empty sequence
我猜猜它將一個空字符串放入最大值,但我不明白爲什麼,在最後一個元素被使用後,while應該終止循環。有人能幫我嗎?