I am trying to end a while loop if a condition is not met.
The purpose of this code is to get the most out of a multiple subjects without going over the maximum hours of work a student is willing to put in.
I have created a dictionary called “subjects” which maps out a certain subject to (value, work) with value as how valuable the subject is, and work as how much work is needed to put into that subject. I am adding up the values of the subjects without going over the maximum hours the student is willing to put in. The subjects that make the most sense are then put into a different dictionary.
Here is the code:
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
The loop ends if maxWork is met, which I have in the code already. The problem is, if maxWork is not met after going through all the subjects, it will continue to loop forever. I need to end the loop after all the items in the dictionary have looped and the condition is not met. I’m guessing I need an “if” statement here, but I just don’t know how to write it. “If all the subjects have been tested and maxWork > tempWork: done = True”
Any help is greatly appreciated.
Thanks
You may just set
done = Trueafter all loops.Further more. Are you really need the
whileloop? I cannot understand your code completely as it is too much to read but I see onlyforloops insidewhileand it looks like other things never change.