だから私は授業のためにナップザック問題を解かなければなりません。これまでのところ、私は次のことを考え出しました。私のコンパレータは、(対応する (value,work) タプルを見て) 2 つのサブジェクトのどちらがより良い選択肢になるかを決定する関数です。
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
問題は、なぜこれが間違っているのか分からないことです。エラーが発生し、コードのどこが間違っているのかわかりません (print ステートメントを投入した後でも)。助けていただければ幸いです、ありがとう!