题解 | #24点运算#
24点运算
http://www.nowcoder.com/practice/7e124483271e4c979a82eb2956544f9d
制造全排列
res = []
def get_all_possibility(left, a): if len(left) == 4: res.append(left[:]) return for aa in a: if aa not in left: left.append(aa) get_all_possibility(left, a) left.pop()
res_1 = [] def change_str(e): if e == '13': return 'K' elif e == '12': return 'Q' elif e== '11': return 'J' elif e == '1': return 'A' else: return e
获取结果
def get_res(u, sum_all, index, calculation): if index == 4: if sum_all == 24: res_1.append(calculation) return if index == 0:
get_res(u, u[index], index + 1, change_str(str(u[index])))
else:
get_res(u, sum_all + u[index], index + 1, calculation + '+' + change_str(str(u[index])))
get_res(u, sum_all - u[index], index + 1, calculation + '-' + change_str(str(u[index])))
get_res(u, sum_all * u[index], index + 1, calculation + '*' + change_str(str(u[index])))
get_res(u, sum_all // u[index], index + 1, calculation + '/' + change_str(str(u[index])))
while True: try: a = input().strip().split() if 'joker' in a or 'JOKER' in a: print('ERROR') continue get_all_possibility([], [0, 1, 2, 3]) choice = [] # print(res) for r in res: m = [] for i in r: if a[i] == 'K': m.append(13) elif a[i] == 'Q': m.append(12) elif a[i] == 'J': m.append(11) elif a[i] == 'A': m.append(1) else: m.append(int(a[i])) if m not in choice: choice.append(m) for c in choice: get_res(c, 0, 0, '') if len(res_1) >= 1: print(res_1[0]) break # print(res_1) if len(res_1) == 0: print('NONE') except EOFError: break