我有一个简单的问题想解决。这是:
([][][]/[][][]) + ([][]/[][]) = 1
目的是用数字 0-9 使上面的陈述成立,并且每个数字只能使用一次。总和的每一部分也等于一半。例如(1/2)+(1/2)=1
我已经开始了,但似乎没有用 . 这是我已经开始的代码
from itertools import permutations
target = 1
for a,b,c,d,e,f,g,h,i,j in permutations(range(0,10), 10):
m = ((100*a + 10*b + c)/(100*d + 10*e + f)) #works out first half of sum
n = ((10*g + h)/(10*i + j)) #works out second half of sum
value = m + n #works out the answer
if value == target and (bool(m) == bool(1/2)) and (bool(n) == bool(1/2)): # checks if answer = the target and makes sure both parts of the sum are equal to a half
print("{}{}{}/{}{}{} + {}{}/{}{} = {}".format(a,b,c,d,e,f,g,h,i,j,target)) #prints out the answer
运行时我的结果是一个空白提示,只是等待,然后什么都没有出现,提示关闭。
当通过 python IDLE 运行它时,我也得到了相同的响应。它等待并且控制台未检测到任何错误。
这表明我的函数没有问题,但是 for 循环有问题,我似乎找不到错误
为什么它不起作用,如何修复?
请您参考如下方法:
如果使用 Python2,添加
from __future__ import division使用浮点除法。否则
1/2等于0。这也是 影响m和n的计算,因为所有的输入都是整数 但您希望m和n为 float 。如果使用 Python3,
target = input("what number do you want to reach? ")是一个错误,因为
input返回一个str。你需要target成为一个 float (或者,正如 DSM 指出的那样,一个分数):target = float(input("what number do you want to reach? "))bool(m)==bool(1/2)是一个错误。没有浮点除法,bool(1/2)等于bool(0)即错误。使用 float 除法,则bool(1/2)为True,但是bool(m)==bool(1/2)将测试bool(m) == True。 对于 0 以外的m的任何浮点值,这将是True。 相反,要检查m是否等于target/2,请使用abs(m - target/2) < epseps的一些小值。 不要使用m == target/2因为检查 float 是否相等可能会失败 由于实数的浮点表示不精确 数。
from __future__ import division
from itertools import permutations
eps = 1e-8
target = float(input("what number do you want to reach? "))
for a,b,c,d,e,f,g,h,i,j in permutations(range(0,10), 10):
m = ((100*a + 10*b + c)/(100*d + 10*e + f)) #works out first half of sum
n = ((10*g + h)/(10*i + j)) #works out second half of sum
value = m + n #works out the answer
if value == target and abs(m - target/2) < eps and abs(n - target/2) < eps: # checks if answer = the target and makes sure both parts of the sum are equal to a half
print("{}{}{}/{}{}{} + {}{}/{}{} = {}".format(a,b,c,d,e,f,g,h,i,j,target)) #prints out the answer
产量
what number do you want to reach? 1
067/134 + 29/58 = 1.0
069/138 + 27/54 = 1.0
073/146 + 29/58 = 1.0
079/158 + 23/46 = 1.0
079/158 + 32/64 = 1.0
093/186 + 27/54 = 1.0
135/270 + 48/96 = 1.0
138/276 + 45/90 = 1.0
145/290 + 38/76 = 1.0
148/296 + 35/70 = 1.0
185/370 + 46/92 = 1.0
186/372 + 45/90 = 1.0
267/534 + 09/18 = 1.0
269/538 + 07/14 = 1.0
273/546 + 09/18 = 1.0
293/586 + 07/14 = 1.0
307/614 + 29/58 = 1.0
309/618 + 27/54 = 1.0
327/654 + 09/18 = 1.0
329/658 + 07/14 = 1.0
351/702 + 48/96 = 1.0
381/762 + 45/90 = 1.0
451/902 + 38/76 = 1.0
481/962 + 35/70 = 1.0
485/970 + 13/26 = 1.0
485/970 + 16/32 = 1.0
485/970 + 31/62 = 1.0
486/972 + 15/30 = 1.0
