我目前有以下两个条件,这两个条件都必须成立:
A B C D+A E F=E F G H和
I C J*E=A B C D
每个字母代表一个从0到9的唯一数字,两个方程都必须为真。 我需要编写一个输出正确答案的Python解决方案,以下是我的代码:
import numpy as np
def solve():
for a in range(0,10):
for b in range(0,10):
for c in range(0,10):
for d in range(0,10):
for e in range(0,10):
for f in range(0,10):
for g in range(0,10):
for h in range(0,10):
for i in range(0,10):
for j in range(0,10):
if len(set([a, b, c, d, e, f, g, h, i, j])) == 10:
icj = 100*i + 10*c + j
e = e
abcd = 1000*a + 100*b + 10*c + d
aef = 100*a + 10*e + f
efgh = 1000*e + 100*f + 10*g + h
if icj * e == abcd and abcd + aef == efgh:
print(icj, e, abcd, aef, efgh)
print(solve())
然而,当我运行它时,它不仅需要运行一段时间,而且还输出“无”。你知道我错在哪里吗
您应该尝试
for x in range(0, 10)
而不是for x in range(0,9)
,因为您正在从0循环到8如果希望以更有效的方式循环,可以使用permutations:
结果:
这是最后的代码:
输出:
除了输入错误,如果只在内部循环中测试所有10位数字是否不同,则此内部循环执行10次10=1000000000次。如果你每次通过考试,你“只”需要10分3628800次传递到此内部循环
您仍然可以更好地更改变量的顺序,因此方程
abc * d == hibj
可以在不需要其他3个变量的情况下进行测试,并且只有在它成立时才能进行更深入的测试。对于这7位数字,您在该循环中输入604800次,只需再输入45次,就可以到达最内部的循环270次尽管它现在运行速度足够快,但仍可以考虑进行更具体的优化:
a,b,c
和h,i,j
,然后计算hibj
是否是abc
的倍数。只有在这种情况下,它才定义了d
,它应该介于0
和9
之间,并且与其他部分不同李>a,b,c,d
,然后首先尝试所有倍数,看它们是否适合b
,然后看相应的h,i,j
是否彼此不同,是否与a,b,c,d
不同李>h
应小于a
,否则d
将大于9
。这使得a
至少1
李>另一种方法是使用SMT/SAT解算器,如Z3。有了这样一个解算器,所有的条件都被公式化,并且通过各种启发式方法来寻找解决方案。示例代码:here和here
这就是代码的样子:
这将输出
a=9, b=3, c=4, d=7, e=2, f=1, g=0, h=6, i=5, j=8
作为唯一的解决方案相关问题 更多 >
编程相关推荐