好的,下面是一个简单的24点小游戏的代码:
import itertools
def calculate(cards):
# 定义运算符和优先级
operators = ['+', '-', '*', '/']
precedence = {'+': 1, '-': 1, '*': 2, '/': 2}
def apply_operator(a, b, operator):
if operator == '+':
return a + b
elif operator == '-':
return a - b
elif operator == '*':
return a * b
elif operator == '/':
return a / b
def evaluate(expression):
operands = []
operators = []
for token in expression:
if isinstance(token, int):
operands.append(token)
elif token in ['+', '-', '*', '/']:
while operators and operators[-1] != '(' and precedence[operators[-1]] >= precedence[token]:
b = operands.pop()
a = operands.pop()
op = operators.pop()
result = apply_operator(a, b, op)
operands.append(result)
operators.append(token)
elif token == '(':
operators.append(token)
elif token == ')':
while operators[-1] != '(':
b = operands.pop()
a = operands.pop()
op = operators.pop()
result = apply_operator(a, b, op)
operands.append(result)
operators.pop()
while operators:
b = operands.pop()
a = operands.pop()
op = operators.pop()
result = apply_operator(a, b, op)
operands.append(result)
return operands[0]
# 生成所有可能的排列组合
permutations = list(itertools.permutations(cards))
# 对每个排列组合进行计算,找到结果为24的表达式
for perm in permutations:
for p1 in range(1, 5):
for p2 in range(1, 5):
for p3 in range(1, 5):
expression = [perm[0], perm[1], perm[2], perm[3]]
expression.insert(1, operators[p1])
expression.insert(3, operators[p2])
expression.insert(5, operators[p3])
# 添加括号
try:
result = evaluate(expression)
if result == 24:
return expression
except:
pass
return None
def game():
print("欢迎来到24点小游戏!")
print("请输入4个数字,以空格分隔:")
nums = input().split()
cards = []
for num in nums:
cards.append(int(num))
expression = calculate(cards)
if expression:
print("恭喜你,找到了一个计算式等于24!")
print("计算式为:", end="")
for i, token in enumerate(expression):
if token in ['+', '-', '*', '/']:
print(" " + token + " ", end="")
else:
print(str(token), end="")
print(" = 24")
else:
print("很遗憾,没有找到计算式等于24!")
game()
运行代码后,程序会要求你输入4个数字。然后程序会找到并输出一个计算式,其结果等于24。例如输入数字2、6、8、3,则输出的计算式为:"(6 - 8 / 3) * 2 = 24"。注意,程序只能找到一个满足条件的计算式,可能有多个满足条件的计算式存在。
希望对你有帮助!祝你游戏愉快!
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。 |