looping through possible combinations of McNuggets packs of 6, 9 and 20
Emile van Sebille
emile at fenx.com
Sun Aug 15 11:58:56 EDT 2010
On 8/15/2010 8:44 AM Baba said...
> Hi John,
>
> Thanks for your submission! I've improved a lot and everone's help so
> far has been thrilling and is very good for my self-study
> motivation :)
>
> ok so i think i'm clear on how to approach this problem and on how to
> write basic but clean Python code to solve it.
>
> The next step is to generalise this code so that other pack quantities
> could be tested: "generalize this idea to work with any size packages
> of McNuggets, not just 6, 9, and 20. For simplicity, however, we will
> assume that nuggets are provided in three different sized packages"
>
> I thought this should be relatively straightforward and it does work
> if i test it for the values 6,9&20 but if i test for 2,3,4 i would
> expect the result to be 1 but it returns nothing
>
Because can_buy still uses denominators 6,9&20 - try packages[0],[1]&[2]
Emile
> def can_buy(n_nuggets,packages):
> for a in range (0,n_nuggets/6+1):
> for b in range (0,n_nuggets/9+1):
> for c in range (0,n_nuggets/20+1):
> #print "trying for %d: %d %d %d" % (n_nuggets,a,b,c)
> if packages[0]*a+packages[1]*b
> +packages[2]*c==n_nuggets:
> return True
> return False
>
> def diophantine_nuggets(x,y,z):
> cbc=0 #cbc=can_buy counter
> packages =[x,y,z]
> for n_nuggets in range(50):
> result=can_buy(n_nuggets,packages)
> if result:
> cbc+=1
> else:
> cbc=0
> if cbc==6:
> solution=n_nuggets-6
> print "Largest number of McNuggets that cannot be bought in
> exact quantity: %d" %(solution)
>
> diophantine_nuggets(2,3,4)
More information about the Python-list
mailing list