5

我想知道是否有办法简化下面的嵌套循环。困难在于每个循环的迭代器都依赖于前一个循环中的东西。这是代码:

# 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
4

3 回答 3

2

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

于 2012-06-20T22:35:19.333 回答
1
  1. 您可以摆脱所有的 int 强制转换。int/int 在 python 中仍然是 int,即整数除法。

  2. 看起来递归会很好地清理这个

    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) 打印计数

于 2012-06-20T23:43:51.567 回答
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)

这有点慢,但它应该工作。

于 2012-06-20T22:41:10.697 回答