您正在解决一个简单的Diophantine方程,并使用以下Python代码来完成它.
## 3a+b+c+d=10
r=10/3
for a in range(r, 0, -1):
r=10-3*a
for b in range(r, 0, -1):
r=10-3*a-b
for c in range(r, 0, -1):
d=10-3*a-b-c
if d>0:
print a, b, c, d, 3*a + b + c + d
在保留代码的基本特征的同时,你如何“很好地”代表它,以便它扩展到在丢番图方程中提供更多变量?
有九种解决方案:
1 6 1
1 5 2
1 4 3
1 3 4
1 2 5
1 1 6
2 3 1
2 2 2
2 1 3
解决方法:
我将创建一个递归生成器函数,其中参数是总和s和每个元素的乘数:
def solve(s, multipliers):
if not multipliers:
if s == 0:
yield ()
return
c = multipliers[0]
for i in xrange(s // c, 0, -1):
for solution in solve(s - c * i, multipliers[1:]):
yield (i, ) + solution
for solution in solve(10, [3, 1, 1]):
print solution
结果:
(2, 3, 1)
(2, 2, 2)
(2, 1, 3)
(1, 6, 1)
(1, 5, 2)
(1, 4, 3)
(1, 3, 4)
(1, 2, 5)
(1, 1, 6)
标签:python,for-loop,representation,diophantine
来源: https://codeday.me/bug/20190829/1764481.html