挑战在于找到小于 N 且总和等于 N 的所有可能的数字组合。例如,当 N 等于:
- 2
- 1+1 - 1 路
- 3
- 2+1
- 1+1+1 - 2种方式
- 4
- 3+1
- 2+2
- 2+1+1
- 1+1+1+1 - 4种方式
等等...
现在在 python 中创建它,以了解我第一次起草此代码的模式:
N=5
for d in drange(0,N,1):
if N-d*4>=0:
for c in drange(0,N,1):
if N-d*4-c*3>=0:
for b in drange(0,N,1):
if N-d*4-c*3-b*2>=0:
for a in drange(0,N,1):
if N-d*4-c*3-b*2-a*1==0:
if sum([d,c,b,a])!=1:
print d,c,b,a
else: break
else:break
else:break
- 然后我将代码更改为适用于 N = 6 及以下的代码:
N=6 for e in drange(0,N,1): if N-e*5>=0: C0 = N-e*5 for d in drange(0,N,1): if C0-d*4>=0: C1 = C0-d*4 for c in drange(0,N,1): if C1-c*3>=0: C2 = C1-c*3 for b in drange(0,N,1): if C2-b*2>=0: C3 = C2-b*2 for a in drange(0,N,1): if C3-a*1==0: if sum([e,d,c,b,a])!=1: print e,d,c,b,a else: break else:break else:break else:break
- 下一个版本包含数组以跟踪数字并节省计算空间:
N=6 Nums = drange2(6-1,-1,-1) Vals = [0]*6 Vars = [0]*6 for Vars[0] in drange(0,N,1): if N-Vars[0]*Nums[0]>=0: Vals[0] = N-Vars[0]*Nums[0] for Vars[1] in drange(0,N,1): if Vals[0]-Vars[1]*Nums[1]>=0: Vals[1] = Vals[0]-Vars[1]*Nums[1] for Vars[2] in drange(0,N,1): if Vals[1]-Vars[2]*Nums[2]>=0: Vals[2] = Vals[1]-Vars[2]*Nums[2] for Vars[3] in drange(0,N,1): if Vals[2]-Vars[3]*Nums[3]>=0: Vals[3] = Vals[2]-Vars[3]*Nums[3] for Vars[4] in drange(0,N,1): if Vals[3]-Vars[4]*Nums[4]==0: if sum([Vars[0],Vars[1],Vars[2],Vars[3],Vars[4]])!=1: print Vars else: break else:break else:break else:break
- 然后我想使这个代码在 N 为 100 的情况下起作用,我让它递归......
N=48 Nums = drange2(N-1,-1,-1) Vals = [0]*N Vars = [0]*(N-1) count=0 def sumCombos(Number,i): if i==0: global count for Vars[i] in xrange(0,i+2,1): z = Number-Vars[i]*Nums[i] if z>=0: Vals[i] = z sumCombos(Number,i+1) else: break elif i<Number-2: for Vars[i] in xrange(0,i+1,1): z = Vals[i-1]-Vars[i]*Nums[i] if z >=0: Vals[i]=z sumCombos(Number,i+1) else: break elif i==Number-2: for Vars[i] in xrange(0,i+3,1): if Vals[i-1]-Vars[i]*Nums[i]==0: count+=1 sumCombos(N,0) print count
- 问题:由于 1000000+ 方法调用需要太多时间,所以有没有一种方法可以让我进行迭代,在不输入所有内容的情况下创建先前的级联效果?我在网站和其他网站上搜索了如何制作涉及 for 循环和 if 语句迭代的递归函数,但这个特定的没有运气。请提供任何智慧——Shaha3