Is there a way to add multiple conditions in a for loop?
n=int(raw_input('enter the number of mcnuggets you want to buy : ')) #total number of mcnuggets you w开发者_开发技巧ant yo buy
for a in range(1,n) and b in range(1,n) and c in range(1,n) :
if (6*a+9*b+20*c==n):
print 'number of packs of 6 are ',a
print 'number of packs of 9 are ',b
print 'number of packs of 20 are',c
i am new to programming and i am learning python.the code above gives errors. Any suggestion.?.
You should use nested loops:
for a in range(1, n):
for b in range(1, n):
for c in range(1, n):
if ...
Or even better:
import itertools
for a, b, c in itertools.product(range(1, n + 1), repeat=3):
if ...
I think you should start the ranges from 0, otherwise you will only get answers that include at least one of each size. You can also make less work for the computer since you know that there will never be more than n/6
packs of 6 required etc. This can be a big saving - for 45 nuggets you only need to test 144 cases compared to 97336
from itertools import product
n=int(raw_input('enter the number of mcnuggets you want to buy : ')) #total number of mcnuggets you want to buy
for a,b,c in product(range(n//6+1), range(n//9+1), range(n//20+1)) :
if (6*a+9*b+20*c==n):
print 'number of packs of 6 are ',a
print 'number of packs of 9 are ',b
print 'number of packs of 20 are',c
itertools.product gives the cartesian product of the 3 ranges. For example
>>> from itertools import product
>>> list(product(range(3),range(4),range(5)))
[(0, 0, 0), (0, 0, 1), (0, 0, 2), (0, 0, 3), (0, 0, 4), (0, 1, 0), (0, 1, 1), (0, 1, 2), (0, 1, 3), (0, 1, 4), (0, 2, 0), (0, 2, 1), (0, 2, 2), (0, 2, 3), (0, 2, 4), (0, 3, 0), (0, 3, 1), (0, 3, 2), (0, 3, 3), (0, 3, 4), (1, 0, 0), (1, 0, 1), (1, 0, 2), (1, 0, 3), (1, 0, 4), (1, 1, 0), (1, 1, 1), (1, 1, 2), (1, 1, 3), (1, 1, 4), (1, 2, 0), (1, 2, 1), (1, 2, 2), (1, 2, 3), (1, 2, 4), (1, 3, 0), (1, 3, 1), (1, 3, 2), (1, 3, 3), (1, 3, 4), (2, 0, 0), (2, 0, 1), (2, 0, 2), (2, 0, 3), (2, 0, 4), (2, 1, 0), (2, 1, 1), (2, 1, 2), (2, 1, 3), (2, 1, 4), (2, 2, 0), (2, 2, 1), (2, 2, 2), (2, 2, 3), (2, 2, 4), (2, 3, 0), (2, 3, 1), (2, 3, 2), (2, 3, 3), (2, 3, 4)]
If you want to have values from multiple sequences in a for
loop then you can use zip
, for example:
for (a,b,c) in zip(xrange(1,n), xrange(1,n), xrange(1,n)) :
....
Of course it is a waste repeating the same range, but judging from the title of your post I guess that using the same range is only and example.
精彩评论