我有一个简单的问题想要解决。这是:
([][][]/[][][]) + ([][]/[][]) = 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) < eps
对于一些还算小的
eps
值。 不要使用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
关于python - 排列不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23638941/