一、题目
二、示例
三、代码
from itertools import permutations
poker = {'A':1, '2':2,'3':3,'4':4,'5':5,'6':6,'7':7,
'8':8,'9':9,'10':10,'J':11,'Q':12,'K':13}
ope = ['+', '-', '*', '/']
def cal_24(cards):
if "joker" in cards or "JOKER" in cards:
print("ERROR")
return None
poker_orders = permutations(cards, 4)
for nums in poker_orders:
for i in range(4):
a = eval(str(poker[nums[0]])+ ope[i] + str(poker[nums[1]]))
for j in range(4):
b = eval(str(a)+ ope[j] + str(poker[nums[2]]))
for k in range(4):
c = eval(str(b)+ ope[k] + str(poker[nums[3]]))
if c == 24:
print(nums[0]+ope[i]+nums[1]+ope[j]+nums[2]+ope[k]+nums[3])
return None
print('NONE')
return None
cal_24(input().split())
四、算法说明
用permutations
函数对输入的四张卡片进行全排列,然后对每一种全排列进行四则运算,从左到右,两两之间进行运算,判断最后结果。
胡萝卜
2022年3月18日22:57:20
我不知道将去向何方,但我已在路上! |
---|
时光匆匆,虽未曾谋面,却相遇于斯,实在是莫大的缘分,感谢您的到访 ! |