definput_card(): if len(sys.argv) == 1: cards = list(map(int, input('Input four card numbers: ').split(' '))) else: cards = sys.argv[1:] try: assert len(cards) == 4 except AssertionError: print('Need four cards!') exit(0)
return cards
defsolve(cards): orders = ['(({}{}{}){}{}){}{}', '({}{}({}{}{})){}{}', '{}{}(({}{}{}){}{})', '{}{}({}{}({}{}{}))', '({}{}{}){}({}{}{})'] result = [] for card in itertools.permutations(cards, r=4): for op in itertools.product(ops, repeat=3): strings = [] for order in orders: strings.append(order.format( card[0], op[0], card[1], op[1], card[2], op[2], card[3]))
for string in strings: try: ret = eval(string) except ZeroDivisionError: continue
if round(ret, ndigits=1) == 24: result.append(string)
return result
defdeduplication(r): return list(set(r))
defdelete(data, index): index = list(set(index)) index.sort(reverse=True)
for i in index: del data[i]
defimprove(result): result = deduplication(result)
# 去第一次括号去重 tmp1 = [] index = [] for s in result: ret = re.search('\([^()]*\)', s).group() tmp1.append(s.replace(ret, str(eval(ret))))
for i, t in enumerate(tmp1): for j, tt in enumerate(tmp1[i + 1:]): if t == tt: index.append(i + j + 1)
# 去第二次括号去重 tmp2 = [] for s in tmp1: ret = re.search('\([^()]*\)', s).group() tmp2.append(s.replace(ret, str(eval(ret))))
for i, t in enumerate(tmp2): for j, tt in enumerate(tmp2[i + 1:]): if t == tt: index.append(i + j + 1)
# 左右对称去重 for i, t in enumerate(tmp2): for j, tt in enumerate(tmp2[i + 1:]): loc = re.search('[+\-*/]{1}', tt).start() tt = tt[loc + 1:] + tt[loc] + tt[:loc] if tt == t: index.append(i + j + 1)
delete(result, index)
return result
defmain():
cards = input_card() result = solve(cards) result = improve(result) for x in result: print(x)