二十四点游戏 python pta
时间: 2023-08-23 17:08:11 浏览: 101
二十四点游戏是一种比较经典的计算游戏,通过随机给出4个数字,玩家需要使用加减乘除等基本运算符号,计算得到24这个数字。以下是一个简单的Python实现:
```python
import itertools
def calculate(a, b, operator):
if operator == '+':
return a + b
elif operator == '-':
return a - b
elif operator == '*':
return a * b
elif operator == '/':
return a / b if b != 0 else None
def check_24(nums):
for p in itertools.permutations(nums):
a, b, c, d = p
for op1 in ['+', '-', '*', '/']:
for op2 in ['+', '-', '*', '/']:
for op3 in ['+', '-', '*', '/']:
# ((a op1 b) op2 c) op3 d
if calculate(calculate(calculate(a, b, op1), c, op2), d, op3) == 24:
return True
# (a op1 b) op2 (c op3 d)
if calculate(calculate(a, b, op1), calculate(c, d, op3), op2) == 24:
return True
# (a op1 (b op2 c)) op3 d
if calculate(calculate(a, calculate(b, c, op2), op1), d, op3) == 24:
return True
# a op1 ((b op2 c) op3 d)
if calculate(a, calculate(calculate(b, c, op2), d, op3), op1) == 24:
return True
return False
if __name__ == '__main__':
nums = input().split()
nums = [int(num) for num in nums]
if check_24(nums):
print('Yes')
else:
print('No')
```
以上代码通过使用`itertools.permutations`产生给定数字的所有排列组合,然后尝试使用4个数字和3个运算符号的组合方式计算是否得到24。如果存在一种组合方式得到了24,则返回Yes,否则返回No。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)