from itertools import permutations, product
from time import sleep
from random import randint
def calculate_postfix(expression):
"""
计算后缀表达式的值
"""
stack = []
for token in expression:
if isinstance(token, (int, float)): # 数字入栈
stack.append(float(token))
else: # 操作符出栈计算
b = stack.pop()
a = stack.pop()
if token == '+':
stack.append(a + b)
elif token == '-':
stack.append(a - b)
elif token == '*':
stack.append(a * b)
elif token == '/':
if abs(b) < 1e-6: # 避免除以零
return None
stack.append(a / b)
return stack[0] if stack else None
def calculate_result(expression):
"""
计算后缀表达式的值
"""
stack = []
for token in expression:
if isinstance(token, (int, float)): # 数字入栈
stack.append(int(token))
else: # 操作符出栈计算
b = stack.pop()
a = stack.pop()
if token == '+':
stack.append(a + b)
print(a, token, b, '=',a+b)
elif token == '-':
stack.append(a - b)
print(a, token, b, '=',a-b)
elif token == '*':
stack.append(a * b)
print(a, token, b, '=',a*b)
elif token == '/':
if abs(b) < 1e-6: # 避免除以零
return None
stack.append(a / b)
print(a, token, b, '=',a/b)
print('结果:',stack[0])
return
def can_make_24(nums):
"""
判断是否可以通过排列和运算符组合得到 24 点
"""
TARGET = 24
EPSILON = 1e-6
operators = ['+', '-', '*', '/']
# 枚举所有数字的排列
for num_perm in permutations(nums):
# 枚举所有运算符的排列
for ops in product(operators, repeat=3):
# 构造所有后缀表达式的可能性
postfix_expressions = [
[num_perm[0], num_perm[1], ops[0], num_perm[2], ops[1], num_perm[3], ops[2]],
[num_perm[0], num_perm[1], num_perm[2], ops[0], ops[1], num_perm[3], ops[2]],
[num_perm[0], num_perm[1], ops[0], num_perm[2], num_perm[3], ops[1], ops[2]],
[num_perm[0], num_perm[1], num_perm[2], ops[0], num_perm[3], ops[1], ops[2]]
]
# 计算每个后缀表达式
for postfix in postfix_expressions:
result = calculate_postfix(postfix)
if result is not None and abs(result - TARGET) < EPSILON:
print("表达式:", postfix)
calculate_result(postfix)
return True # 找到满足条件的解即可返回 True
return False # 遍历所有组合后仍未找到解
def generate_num():
nums = [randint(1,25) for _ in range(4)]
print(nums)
return nums
# 测试用例
nums=generate_num()
sleep(10)
if can_make_24(nums):
print("可以拼出 24 点!")
else:
print("无法拼出 24 点!")