您正在求解一个简单的丢番图方程,并使用以下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
发布于 2015-04-20 01:11:25
我将创建一个递归生成器函数,其中的参数是总和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)
发布于 2015-04-20 00:24:00
您可以首先定义每个变量的可能值,然后使用itertool
的product
遍历所有可能的组合
from itertools import product
## 3a+b+c+d=10
A = range(10, 0, -1)
B = range(10, 0, -1)
C = range(10, 0, -1)
for a, b, c in product(A, B, C):
d = 10 - 3 * a - b - c
if d > 0:
print a, b, c, d, 3 * a + b + c + d
输出:
2 2 1 1 10
2 1 2 1 10
2 1 1 2 10
1 5 1 1 10
1 4 2 1 10
1 4 1 2 10
1 3 3 1 10
1 3 2 2 10
1 3 1 3 10
1 2 4 1 10
1 2 3 2 10
1 2 2 3 10
1 2 1 4 10
1 1 5 1 10
1 1 4 2 10
1 1 3 3 10
1 1 2 4 10
1 1 1 5 10
请注意,通过对所有循环使用相同的r
,您所做的工作比实际需要的要多。因此,这取决于应用程序,这个解决方案是否有帮助。
https://stackoverflow.com/questions/29732115
复制相似问题