题意
给到扑克牌中的四张卡片,算24点。卡片A的值为1,J为11,Q为12,K为13,joker和JOKER出现时输出ERROR。如果有解,输出解的表达式,如果无解,输出ERROR。
import sys
from itertools import permutations
from itertools import combinations
获取输入
# input
s = sys.stdin.readline().strip('\n')
cards = s.split(' ')
将A,J,Q,K转为数字
# transform card name string to nums
error = False
nums = []
for c in cards:
if c == 'JOKER' or c == 'joker':
error = True
elif c == 'A':
nums.append(1)
elif c == 'J':
nums.append(11)
elif c == 'Q':
nums.append(12)
elif c == 'K':
nums.append(13)
elif c.isdigit():
nums.append(int(c))
使用permutations获取数字可能的排列
p_nums = [list(x) for x in permutations(nums)]
列出符号可能的排列
# list all possible set of choice of operators and nums
operators = ['+', '-', '*', '/']
p_op = []
t = ""
for i in range(4):
for j in range(4):
for k in range(4):
t = str(operators[i]) + str(operators[j]) + str(operators[k])
p_op.append(t)
验证符号和数字的组合是否能算出24点
#print(p_nums)
#print(p_op)
found = False
for ns in p_nums:
if found:
break
for ops in p_op:
if found:
break
left = eval(str(ns[0]) + ops[0] + str(ns[1]))
if left != int(left) or left > 24:
continue
mid = eval(str(left) + ops[1] + str(ns[2]))
if mid != int(mid) or mid > 24:
continue
right = eval(str(mid) + ops[2] + str(ns[3]))
if right != int(right) or right > 24:
continue
s = str(ns[0]) + ops[0] + str(ns[1]) + ops[1] + str(ns[2]) + ops[2] + str(ns[3])
t = []
if eval(s) == 24:
for i in range(4):
if ns[i] == 'A':
t.append(1)
elif ns[i] == 'J':
t.append(11)
elif ns[i] == 'Q':
t.append(12)
elif ns[i] == 'K':
t.append(13)
else:
t.append(str(ns[i]))
found = True
s = str(t[0]) + ops[0] + str(t[1]) + ops[1] + str(t[2]) + ops[2] + str(t[3])
print(s)