looping through possible combinations of McNuggets packs of 6, 9 and 20

Mel mwilson at the-wire.com
Sat Aug 14 11:49:28 EDT 2010


Baba wrote:

> def can_buy(n_nuggets):
>    for a in range (0,n_nuggets):
>        for b in range (0,n_nuggets):
>            for c in range (0,n_nuggets):
>                #print "trying for %d: %d %d %d" % (n_nuggets,a,b,c)
>                if 6*a+9*b+20*c==n_nuggets:
>                    return [a,b,c]
>    return []
>
> for n_nuggets in range(50):
>     result1 = can_buy(n_nuggets)
>     result2 = can_buy(n_nuggets+1)
>     result3 = can_buy(n_nuggets+2)
>     result4 = can_buy(n_nuggets+3)
>     result5 = can_buy(n_nuggets+4)
>     result6 = can_buy(n_nuggets+5)
>     if result1!=[] and result2!=[] and result3!=[] and result4!=[] and
> result5!=[] and result6!=[]:
>      if (n_nuggets+5)-n_nuggets==5:
>         print n_nuggets-1
>         break
>
> i suppose this can be tweaked to make it shorter? For instance i
> wonder if i can do the same with less variable to be defined?

That can_buy function is a computational heavyweight -- very
repetitive when called inside a loop. It could be cheaper to compute a
list of quantities that can be purchased, then check to see what's in
the list -- or the set, if you optimize a bit more.

	Mel.




More information about the Python-list mailing list