我目前有以下两种情况,这两种情况都必须成立:
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()) 但是,当我运行这个程序时,它不仅需要一段时间才能运行,还会输出“无”。对我哪里出错有什么想法吗?
发布于 2020-07-15 10:14:49
您应该尝试for x in range(0, 10)而不是for x in range(0,9),因为您正在从0循环到8。
如果您想以更有效的方式循环,可以使用排列
from itertools import permutations
for a, b, c, d, e, f, g, h, i, j in permutations(range(0, 10), 10):
print(a, b, c, d, e, f, g, h, i, j)结果:
0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 9 8
...
9 8 7 6 5 4 3 2 0 1
9 8 7 6 5 4 3 2 1 0这里是最后的代码:
import numpy as np
from itertools import permutations
def solve():
for a, b, c, d, e, f, g, h, i, j in permutations(range(0, 10), 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(a, b, c, d, e, f, g, h, i, j)
solve()产出:
934 7 6538 672 7210
6 5 3 8 7 2 1 0 9 4https://stackoverflow.com/questions/62912493
复制相似问题