Problem Set 2 - here's my code. Did others do it in the same way?
n=0 #number of nuggets: our value being tested and our value to count bestSoFar=0 #highest number of nuggets that CANNOT be bought packages = (6,9,20) # variable that contains package sizes Status='unavailable' #indicates if n is an available combination of nuggets, default is unavilable for n in range(1, 150): # only search for solutions up to size 150 for a in range(0,50): #no need for a large range as we are only examining up to 150 nuggets for b in range(0,50): for c in range(0,50): x=packages[0]*a+packages[1]*b+packages[2]*c if x==n: Status='available' if Status=='unavailable': bestSoFar=n Status='unavailable' #reset status print 'Largest number of McNuggets that cannot be bought in exact quantity: ',bestSoFar
there are many ways of solving problem
I suppose so - it's a little bit frustrating that there is no 'right' answer ... guess i should get used to it
well anyway it's better to write optimised code which takes least time, least memory
yep, there are many right ways and some are more right than others http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html
oh i know this from __future__ import braces :DD
No need to initialize n ahead of time, the for loop does that. You are checking much farther than necessary with your for loops - up to 1715 nuggets when you are checking up to 49 of each package amount. Also, if this is problem 3, you need to write it so that it stops after it finds 6 consecutive amounts which can be found.
thanks . I've updated my code accordingly. I found it a bit difficult to measure where we had 6 consecutive amounts. In the end I stuck the set of valid solutions for n into a tuple and used if ntuple[-1]-ntuple[-6]==5 as the condition for stopping the program. It was a pain to write though, particularly setting up the tuple in the first place. I used the below assignment which is pretty ugly but it was the only way I could get it to work: ntuple=[0,0,0,0,0,0,0] # tuple to store solutions for n nuggets
you could initialize a counter and increment it whenever Status = 'available' and reset it if Status = 'unavailable'. You could then use counter to exit. You may have to use a while loop instead of a for loop to exit. Otherwise, you could just use your counter as a condition to keep checking solutions. You'd still go through the loop until n = 149, but you'd only look for solutions if counter < 6.
Join our real-time social learning platform and learn together with your friends!