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

MRAB python at mrabarnett.plus.com
Sat Aug 14 18:44:15 CEST 2010


Baba wrote:
> On Aug 13, 8:25 pm, Ian Kelly <ian.g.ke... at gmail.com> wrote:
> 
>> It's not.  You're not just trying to find the sixth value that can be
>> bought in exact quantity, but a sequence of six values that can all be
>> bought in exact quantity.  The integers [6, 9, 12, 15, 18, 20] are not
>> sequential.
> 
> Hi Ian,
> 
> Thanks for stating the obvious. I obviously hadn't understood a
> fundamental part of the theorem which states that 6 SEQUENTIAL passes
> must be found! That's a good lesson learned and will help me in future
> exercises to make sure i understand the theory first. Thanks again!
> 
> Ok so with your and News123's help (no offence to all others but i
> need to keep it simple at this stage)i was able to find the solution:
> 43
> 
> my code is probably not elegant but a huge step forward from where i
> started:
> 
> 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?
> 
Increase the number of nuggets one by one and keep a count of the number
of consecutive successes.

If you can buy a number of nuggets exactly, increment the count,
otherwise reset the count.

When the count reaches 6 you know that you're at the end of a sequence
of consecutive successes.



More information about the Python-list mailing list