Python 中的递归函数调用
Recursive function call in Python
我是 Python 的初学者,想解决以下问题:给定一个 n 整数列表和一个整数结果正确的运算符 (+, -, *, /) 应找到解决相应的简单数学方程式。
示例:
对于 numbers = [2, 3, 4, 1] 和 result=13 应找到以下解决方案:
2 + 3 * 4 - 1 = 13.
我写了下面的代码,它通过使用 3 个嵌套的 for 循环(其中运算符交替进行)的蛮力方法找到了 n=4 的解决方案。但是,当我尝试编写 n 是任意的算法时,我很挣扎。这可以通过递归函数调用来解决吗?如果可以,如何解决?
numbers = [2, 3, 4, 1]
result = 13
op = ['+','-','*', '/']
Found=0
for i in op:
for j in op:
for k in op:
#Build string for left side of the equation: e.g. '2 + 3 + 4 + 1'
exp = str(numbers[0]) + i + str(numbers[1]) + j + str(numbers[2]) + k + str(numbers[3])
if eval(exp) == result:
Found += 1
if Found == 1:
print('Found Solution(s):')
print(f'{numbers[0]} {i} {numbers[1]} {j} {numbers[2]} {k} {numbers[3]} = {result}')
if Found == 0:
print('No solution found!')
不是递归解决方案,效率不及您的解决方案,但它可以处理任意数量的操作。
itertools.product
用于获取你想要的,如果我能想出一个有效的递归解决方案我会编辑这个。
from itertools import product
def check_result(numbers,result):
op = ['+','-','*', '/']
for i in product(op,repeat=len(numbers)-1):
t=[None]*(len(numbers)+len(i))
t[::2],t[1::2]=numbers,i
t=[str(i) for i in t]
expr=''.join(t)
if eval(expr)==result:
return 'Found'
return 'Not Found'
print(check_result([2, 3, 4, 1],13)) # Found
print(check_result([2, 3, 4, 1,2],14)) # Found
print(check_result([2, 3, 4, 1,2,3,3,1,2],242)) # Not Found
我是 Python 的初学者,想解决以下问题:给定一个 n 整数列表和一个整数结果正确的运算符 (+, -, *, /) 应找到解决相应的简单数学方程式。
示例:
对于 numbers = [2, 3, 4, 1] 和 result=13 应找到以下解决方案:
2 + 3 * 4 - 1 = 13.
我写了下面的代码,它通过使用 3 个嵌套的 for 循环(其中运算符交替进行)的蛮力方法找到了 n=4 的解决方案。但是,当我尝试编写 n 是任意的算法时,我很挣扎。这可以通过递归函数调用来解决吗?如果可以,如何解决?
numbers = [2, 3, 4, 1]
result = 13
op = ['+','-','*', '/']
Found=0
for i in op:
for j in op:
for k in op:
#Build string for left side of the equation: e.g. '2 + 3 + 4 + 1'
exp = str(numbers[0]) + i + str(numbers[1]) + j + str(numbers[2]) + k + str(numbers[3])
if eval(exp) == result:
Found += 1
if Found == 1:
print('Found Solution(s):')
print(f'{numbers[0]} {i} {numbers[1]} {j} {numbers[2]} {k} {numbers[3]} = {result}')
if Found == 0:
print('No solution found!')
不是递归解决方案,效率不及您的解决方案,但它可以处理任意数量的操作。
itertools.product
用于获取你想要的,如果我能想出一个有效的递归解决方案我会编辑这个。
from itertools import product
def check_result(numbers,result):
op = ['+','-','*', '/']
for i in product(op,repeat=len(numbers)-1):
t=[None]*(len(numbers)+len(i))
t[::2],t[1::2]=numbers,i
t=[str(i) for i in t]
expr=''.join(t)
if eval(expr)==result:
return 'Found'
return 'Not Found'
print(check_result([2, 3, 4, 1],13)) # Found
print(check_result([2, 3, 4, 1,2],14)) # Found
print(check_result([2, 3, 4, 1,2,3,3,1,2],242)) # Not Found