python24点小游戏代码
时间: 2023-09-04 17:09:32 浏览: 39
以下是一个简单的 Python 24 点小游戏代码,希望对你有所帮助:
```python
import itertools
def calc24(nums):
ops = ['+', '-', '*', '/']
for a, b, c, d in itertools.permutations(nums):
for op1, op2, op3 in itertools.product(ops, repeat=3):
exp = f'(({a}{op1}{b}){op2}{c}){op3}{d}'
try:
if abs(eval(exp) - 24) < 1e-9:
return exp
except ZeroDivisionError:
pass
return None
def main():
while True:
nums = input('请输入四个数字(空格分隔):').split()
if len(nums) != 4:
print('输入错误,请重新输入!')
continue
nums = list(map(int, nums))
exp = calc24(nums)
if exp:
print(f'恭喜你,算式 {exp} 的结果是 24!')
else:
print('很遗憾,没有算式的结果是 24。')
if __name__ == '__main__':
main()
```
运行代码后,会提示用户输入四个数字,然后计算这四个数字是否能通过加、减、乘、除四种运算符得到 24。如果能,则输出算式,否则输出提示信息。