我想不出更好的标题,因为一个合适的标题可能需要完整的解释。此外,组合可能会产生误导,因为问题将涉及排列。
我想要完成的是在以下问题中超越 Python 中的蛮力方法:给定 4 个基本操作 [+,-,*,/] 和从 1 到 9 的数字,并给出 5 位数字的所有可能组合以及导致给定数字(视为整数)的 4 次不重复(排列)运算,如 1+5*9-3/7=45, 1-2/3+9*5=45,.. . 获取从可能的最低值到可能的最高值的所有整数,并找出空间中的所有整数是否存在。
我用蛮力的初步尝试如下:
def brute_force(target):
temp = 0
x = [i for i in range(1,10)]
numbers = [str(i) for i in x]
operators = ["+","-","*","/"]
for values in permutations(numbers,5):
for oper in permutations(operators):
formula = "".join(o + v for o,v in zip([""]+list(oper),values))
if round(eval(formula)) == int(target):
temp += 1
if temp > 0:
return True
else:
return False
for i in range(-100,100): …Run Code Online (Sandbox Code Playgroud)