有没有一种生成数字列表 (0-9) 的好方法,重复且长度为 6,这样总和为 N,比如 20。例如:
004673 -> 4+6+7+3=20
121673 -> 1+2+1+6+7+3=20
...
谢谢
最佳答案
['{0:06}'.format(i) for i in xrange(1000000) if sum(map(int,str(i))) == 20]
执行此操作并需要大约 5 秒才能返回所有 35127 个数字。
更新 - 作为奖励,丑陋但速度快得多(快约 40 倍)的版本出现了:
result = []
for a in xrange(10):
for b in xrange(10):
for c in xrange(10):
if a+b+c <= 20:
for d in xrange(10):
if 2 < a+b+c+d <= 20:
for e in xrange(10):
if 10 < a+b+c+d+e <= 20:
f = 20 - (a+b+c+d+e)
result.append(''.join(map(str, [a,b,c,d,e,f])))
关于python - 找到总和为 N 的所有组合的好方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8617455/