所以我必須解決類的揹包問題。到目前爲止,我已經提出了以下內容。我的比較器是決定哪兩個主題是更好的選項(通過查看相應(值,工作)元組)的函數。揹包問題(經典)
我決定對工作量小於maxWork的可能主題進行迭代,並且爲了在任何給定回合中找到哪個主題是最佳選項,我將我最近的主題與我們沒有使用過的所有其他主題進行了比較然而。
def greedyAdvisor(subjects, maxWork, comparator):
"""
Returns a dictionary mapping subject name to (value, work) which includes
subjects selected by the algorithm, such that the total work of subjects in
the dictionary is not greater than maxWork. The subjects are chosen using
a greedy algorithm. The subjects dictionary should not be mutated.
subjects: dictionary mapping subject name to (value, work)
maxWork: int >= 0
comparator: function taking two tuples and returning a bool
returns: dictionary mapping subject name to (value, work)
"""
optimal = {}
while maxWork > 0:
new_subjects = dict((k,v) for k,v in subjects.items() if v[1] < maxWork)
key_list = new_subjects.keys()
for name in new_subjects:
#create a truncated dictionary
new_subjects = dict((name, new_subjects.get(name)) for name in key_list)
key_list.remove(name)
#compare over the entire dictionary
if reduce(comparator,new_subjects.values())==True:
#insert this name into the optimal dictionary
optimal[name] = new_subjects[name]
#update maxWork
maxWork = maxWork - subjects[name][1]
#and restart the while loop with maxWork updated
break
return optimal
問題是我不知道爲什麼這是錯誤的。我遇到了錯誤,並且我不知道我的代碼在哪裏出錯(即使在拋出打印語句後)。幫助將不勝感激,謝謝!
你試圖解決它近似,或者到底是什麼?因爲使用簡單的貪婪算法只能大致解決這個問題,並且與最優質量相比,它的質量沒有保證。 – 2011-04-15 23:09:29
你如何測試/運行這個功能?請添加更多代碼。 – 2011-04-15 23:09:34
我只是試圖解決它。 – Glassjawed 2011-04-15 23:35:39