有没有办法在for循环中添加多个条件?

时间:2011-07-21 11:01:21

标签: python for-loop conditional

    n=int(raw_input('enter the number of mcnuggets you want to buy : ')) #total number of               mcnuggets you want 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

我是编程新手,我正在学习python。上面的代码给出了错误。有任何建议。?。

3 个答案:

答案 0 :(得分:4)

您应该使用嵌套循环:

for a in range(1, n):
    for b in range(1, n):
        for c in range(1, n):
            if ...

甚至更好:

import itertools

for a, b, c in itertools.product(range(1, n + 1), repeat=3):
    if ...

答案 1 :(得分:3)

我认为您应该从0开始范围,否则您将只获得包含每种尺寸中至少一种的答案。你也可以减少计算机的工作量,因为你知道永远不会超过n/6包6个等等。这可以节省很多 - 对于45个掘金你只需要测试144个案例而不是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给出了3个范围的cartesian product。例如

>>> 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)]

答案 2 :(得分:1)

如果您希望在for循环中包含多个序列的值,则可以使用zip,例如:

for (a,b,c) in zip(xrange(1,n), xrange(1,n), xrange(1,n)) :
    ....

当然浪费重复相同的范围,但从帖子的标题来看,我猜使用相同的范围仅仅是例子。