非常抱歉再次给您带来困扰。我看到了问题所在。在 evaluate 函数中,我没有正确处理一元运算符的情况,导致栈为空时出现错误。
以下是修复后的代码:
import itertools
def calculate(cards):
# 定义运算符和优先级
operators = ['+', '-', '*', '/']
precedence = {'+': 1, '-': 1, '*': 2, '/': 2}
def evaluate(expression):
stack = []
for token in expression:
if isinstance(token, int):
stack.append(token)
else:
if token == '(':
stack.append(token)
elif token == ')':
while stack[-2] != '(':
b = stack.pop()
a = stack.pop()
op = stack.pop()
result = eval(str(a) + op + str(b))
stack.append(result)
stack.pop() # 弹出 '('
else:
while (stack and stack[-1] in operators and
precedence[token] <= precedence[stack[-1]]):
b = stack.pop()
a = stack.pop()
op = stack.pop()
result = eval(str(a) + op + str(b))
stack.append(result)
stack.append(token)
while len(stack) >= 3:
b = stack.pop()
a = stack.pop()
op = stack.pop()
result = eval(str(a) + op + str(b))
stack.append(result)
return stack[0]
# 生成所有可能的排列组合
permutations = list(itertools.permutations(cards))
for perm in permutations:
operators_permutations = list(itertools.product(operators, repeat=3))
for operators in operators_permutations:
expression = [perm[0], operators[0], perm[1], operators[1], perm[2], operators[2], perm[3]]
if evaluate(expression) == 24:
return expression
return None
def game():
print("欢迎来到24点小游戏!")
cards = input("请输入4个数字,以空格分隔:").split()
cards = [int(card) for card in cards]
expression = calculate(cards)
if expression:
print("成功找到解答!括号可以任意添加,以下是一种可能的表达式:")
print("({} {} {}) {} ({}) {} ({} {} {})".format(expression[0], expression[1], expression[2], expression[3], expression[4], expression[5], expression[6], expression[7], expression[8]))
else:
print("很抱歉,无法找到解答。")
game()
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。 |