Python:简化嵌套的FOR循环?

时间:2012-06-20 22:29:15

标签: python loops for-loop nested

我想知道是否有办法简化下面的嵌套循环。困难在于每个循环的迭代器取决于之前循环的内容。这是代码:

# Find the number of combinations summing to 200 using the given list of coin

coin=[200,100,50,20,10,5,2,1]

total=[200,0,0,0,0,0,0,0]
# total[j] is the remaining sum after using the first (j-1) types of coin
# as specified by i below

count=0
# count the number of combinations

for i in range(int(total[0]/coin[0])+1):
    total[1]=total[0]-i*coin[0]
    for i in range(int(total[1]/coin[1])+1):
      total[2]=total[1]-i*coin[1]
      for i in range(int(total[2]/coin[2])+1):
          total[3]=total[2]-i*coin[2]
          for i in range(int(total[3]/coin[3])+1):
              total[4]=total[3]-i*coin[3]
              for i in range(int(total[4]/coin[4])+1):
                  total[5]=total[4]-i*coin[4]
                  for i in range(int(total[5]/coin[5])+1):
                      total[6]=total[5]-i*coin[5]
                      for i in range(int(total[6]/coin[6])+1):
                          total[7]=total[6]-i*coin[6]
                          count+=1

print count

3 个答案:

答案 0 :(得分:2)

我建议查看http://labix.org/python-constraint这是一个Python约束库。其中一个示例文件实际上是硬币的排列达到特定金额,一旦您指定规则,它就会为您处理。

答案 1 :(得分:1)

  1. 你可以摆脱所有的int铸造。 int / int仍然是python中的int,即整数除法。

  2. 看起来像Recursion会清理它

    count  = 0
    coin=[200,100,50,20,10,5,2,1]
    total=[200,0,0,0,0,0,0,0]
    
    def func(i):
        global count,total,coin
        for x in range(total[i-1]/coin[i-1]+1):
            total[i]=total[i-1]-x*coin[i-1]
            if (i == 7):
                count += 1
            else:
                func(i+1)
    

    FUNC(1) 打印数量

答案 2 :(得分:0)

combinations = set()
for i in range(len(coins)):
  combinations = combinations | set(for x in itertools.combinations(coins, i) if sum(x) == 200)
print len(combinations)

它有点慢,但它应该有效。