如果未滿足條件,則試圖結束while循環。如果條件未滿足,則結束while循環
這段代碼的目的是爲了獲得最大的多學科的但不超過最高工時的學生願意把英寸
我創建了一個名爲「科目」字典它映射(有價值,有價值,有工作價值)這個主題是多麼寶貴,並且需要多少工作才能投入到這個主題中。我將這些科目的價值加起來,而不會超過學生願意投入的最長時間。然後將最有意義的科目放入不同的字典中。
下面是代碼:如果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)
"""
bestVal = {}
tempVal = 0
high = 0
count = 0
tempDict = {}
tempWork = 0
currentBest = None
done = False
while done == False:
for k in range(len(subjects)+1):
for i in subjects:
for j in subjects:
if i not in bestVal:
sub1 = subjects[i][0]
sub2 = subjects[j][0]
work1 = subjects[i][1]
work2 = subjects[j][1]
if tempWork >= maxWork:
print('tempWork is', tempWork)
print('bestVal is', bestVal)
print('high is', high)
print('tempVal is', tempVal)
print()
return
print('sub1 is', sub1)
print('sub2 is', sub2)
print('work1 is', work1)
print('work2 is', work2)
maxVal = comparator(sub1, sub2)
print('count is', count)
count += 1
if maxVal == True:
print('sub1+tempVal is', sub1+tempVal)
print('tempVal is', tempVal)
print()
if work1 + tempWork > tempWork and tempWork + work1 <= maxWork:
high += tempVal+sub1
tempWork += work1
tempVal = sub1 +tempVal
print('sub1', sub1)
print('work1 is', work1)
print('tempWork is', tempWork)
print('tempVal is', tempVal)
print('tempWork is', tempWork)
bestVal[i] = subjects[i]
print('bestVal is', bestVal)
print()
else:
break
循環結束,這是我在代碼了。問題是,如果maxWork在經過所有主題後沒有被滿足,它將會一直循環。在詞典中的所有項目都循環並且條件未滿足之後,我需要結束循環。我猜我在這裏需要一個「if」聲明,但我不知道如何編寫它。 「如果所有主題都經過測試並且maxWork> tempWork:done = True」
任何幫助都非常感謝。
感謝
哇,這正是我所期待的。謝謝。 – CastorTroy 2011-12-16 04:15:27
我知道這是一團糟,我只是停留在這個while循環的事情上,需要知道如何去做,即使我不需要它。我要回去清理它。我很感激幫助。 – CastorTroy 2011-12-16 04:34:54
抱歉,但這是一個不好的補丁。 while循環絕對是不必要的 – joaquin 2011-12-17 10:29:11