根据题目,不能用括号,从左到右计算(就不会出现整除0的情况)
用itertools的permutations和product方法生成序列,
用eval计算
以上,提供个思路吧。
import itertools
nums = [None, 'A']+list('23456789')+['10', 'J', 'Q', 'K']
while True:
try:
s = input()
if 'joker' in s.lower(): print('ERROR')
else:
a = [str(nums.index(i)) for i in s.split()]
isfind = False
for x1, x2, x3, x4 in itertools.permutations(a):
if isfind: break
for op1, op2, op3 in itertools.product('+-*/', '+-*/', '+-*/'):
res = ''.join(['((', x1, op1, x2, ')', op2, x3, ')', op3, x4])
if abs(eval(res)-24)<0.01:
print(''.join([nums[int(x1)], op1,
nums[int(x2)], op2,
nums[int(x3)], op3,
nums[int(x4)]]))
isfind = True
break
if not isfind:
print('NONE')
except:
break
京公网安备 11010502036488号