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

MRAB python at mrabarnett.plus.com
Thu Aug 12 15:34:34 EDT 2010


Baba wrote:
> Hi News123
> 
> Thank You for helping me out. Indeed i am not looking for the code but
> rather for hints that direct my reasoning as well as hints as to how
> to write basic programs like this.
> 
> You have broken down the approach into 2 parts. I have tried to solve
> part 1 but i'm not quite there yet. Here's my code:
> 
> def can_buy(n_nuggets):
>     for a in range (1,n_nuggets):
>         for b in range (1,n_nuggets):
>             for c in range (1,n_nuggets):
>                 if 6*a+9*b+20*c==n_nuggets:
>                     #print a,b,c,'n_nuggets=',n_nuggets
>                     return True
>                 else:
>                     return False
> 
> 
> can_buy(55)
> 
> as you can see i am trying to loop through all combinations of values
> bewtween 1 and n_nuggets and when the equation resolves it should
> return True, else it should return False.
> 
> I was hoping that when i then call my function and ask it to test a
> value nothing happens. What is wrong? My syntax? My semantic? Both?
> 
Think about it this way.

How many packs of 20 would you need? You don't want too many, but too
few is OK.

Then, how many packs of 9 for the remaining nuggets? (Again, you don't
want too many.)

Then, how many packs of 6?

If all the nuggets are accounted for, good, otherwise reduce the number
of one of the packs and try again. Repeat as necessary.

A couple of 'for' loops will do it.



More information about the Python-list mailing list