用python38写一份可以输入数字的24点游戏算法的程序
下面是一个使用Python 3.8编写的可以输入数字的24点游戏算法程序的示例:
from itertools import permutations, product
def evaluate(exp):
# 运算符优先级
precedence = {'+': 1, '-': 1, '*': 2, '/': 2}
# 运算符栈和操作数栈
op_stack = []
num_stack = []
for token in exp:
if token.isdigit():
num_stack.append(int(token))
else:
while op_stack and precedence[op_stack[-1]] >= precedence[token]:
op = op_stack.pop()
num2 = num_stack.pop()
num1 = num_stack.pop()
if op == '+':
result = num1 + num2
elif op == '-':
result = num1 - num2
elif op == '*':
result = num1 * num2
elif op == '/':
result = num1 / num2
num_stack.append(result)
op_stack.append(token)
while op_stack:
op = op_stack.pop()
num2 = num_stack.pop()
num1 = num_stack.pop()
if op == '+':
result = num1 + num2
elif op == '-':
result = num1 - num2
elif op == '*':
result = num1 * num2
elif op == '/':
result = num1 / num2
num_stack.append(result)
return num_stack[0]
def solve_24(nums):
ops = ['+', '-', '*', '/']
for perm in permutations(nums):
for op1, op2, op3 in product(ops, repeat=3):
exp = [str(perm[0]), op1, str(perm[1]), op2, str(perm[2]), op3, str(perm[3])]
if evaluate(exp) == 24:
return exp
return None
# 输入四个数字
nums = [int(input(f"请输入第{i+1}个数字: ")) for i in range(4)]
solution = solve_24(nums)
if solution:
print("找到解:", ' '.join(solution), "= 24")
else:
print("无解")
这个程序使用了迭代器permutations和product来生成数字和运算符的所有排列和组合,然后通过逆波兰表达式的计算方式来计算表达式的值。最后,程序会输出解(如果存在)或者无解的信息
原文地址: https://www.cveoy.top/t/topic/hLIY 著作权归作者所有。请勿转载和采集!