looping through possible combinations of McNuggets packs of 6, 9 and 20
member thudfoo
thudfoo at opensuse.us
Sat Aug 14 12:40:29 EDT 2010
On 8/14/10, Baba <raoulbia at gmail.com> 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?
>
> tnx
> Baba
>
One tweak:
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):
if (can_buy(n_nuggets)
and can_buy(n_nuggets+1)
and can_buy(n_nuggets+2)
and can_buy(n_nuggets+3)
and can_buy(n_nuggets+4)
and can_buy(n_nuggets+5)):
print n_nuggets - 1
break
More information about the Python-list
mailing list