最近,我读了一个数学问题鼓励我写一个程序.它要求每次安排数字0-9,以便xx xxx / xx xxx = 9.我写了一个
python程序来找到解决方案,并确保数字不同有点麻烦.我找到了一种使用嵌套whiles和ifs的方法,但我对它并不满意.
b,c,x,y,z = 0,0,0,0,0 #I shortened the code from b,c,d,e,v,w,x,y,z
for a in range (10):
while b < 10:
if b != a:
while c < 10:
if c != b and c != a:
while x < 10:
if x != c and x != b and x != a:
while y < 10:
if y != x and y != c and y != b and y != a:
while z < 10:
if z != y and if z != z and y != c and z != b and z != a:
if (a*100 + b*10 + c)/(x*100 + y*10 + z) == 9:
print ()
print (str (a*100 + b*10 + c) + "/" + str (x*100 + y*10 + z)
z += 1
z = 0
y += 1
y,z = 0,0
x += 1
x,y,z = 0,0,0
c += 1
c,x,y,z = 0,0,0,0
b += 1
b,c,x,y,z = 0,0,0,0,0
正如您所看到的,代码非常长且重复,甚至是缩短的形式.在我的笔记本电脑上运行它需要将近一分钟(我的笔记本电脑是新的).我已经搜索了答案,但我只找到了生成随机数的方法.我也尝试过使用itertools.permutations,但这只显示了排列,而不是创建一个数字.
生成所有十个数字需要太长时间,我想知道是否有更快,更简单的方法,并使用python 3进行解释.
谢谢
最佳答案 适应Wayne Werner的解决方案,您可以执行此操作以添加数字唯一性约束(假设Python 3):
[(9*num, num)
for num in range(10000, 100000 // 9)
if len(set(str(num) + str(num * 9))) == 10]
这在我的机器上运行1.5毫秒.
请注意,您只能检查10000到100000/9 = 11111之间的数字.
如果你想允许前面的零,你可以这样做:
[(9*num, num)
for num in range(0, 100000 // 9)
if len(set(("%05d" % num) + ("%05d" % (num * 9)))) == 10]
这个需要15毫秒.