Last active
October 8, 2016 13:58
-
-
Save fy0/01d701cada43be6e4bedf8b4ad222dc4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import re | |
import itertools | |
t = input('输入四个数:') | |
nums = list(map(int, re.split('\s+', t))) | |
div = lambda x, y : x // y | |
signs = [int.__add__, int.__sub__, int.__mul__, div] | |
signs_txt = {signs[0]: '+', signs[1]: '-', signs[2]: '*', signs[3]: '/'} | |
signs_to_txt = lambda x: signs_txt[x] | |
def pick_three(data): | |
ret = [] | |
for a in data: | |
for b in data: | |
for c in data: | |
ret.append([a, b, c]) | |
return ret | |
def calc(sign_lst, num_lst): | |
for i in sign_lst: | |
a = num_lst.pop() | |
b = num_lst.pop() | |
num_lst.append(i(a, b)) | |
return num_lst.pop() | |
def pretty(sign_lst, num_lst): | |
ret = [] | |
sign_lst.append('') | |
for i in range(len(num_lst)): | |
ret.append(str(num_lst[i])) | |
if sign_lst[i] in ['*', '/']: | |
ret.insert(0, '(') | |
ret.append(')') | |
ret.append(str(sign_lst[i])) | |
return ' '.join(ret) | |
for i in pick_three(signs): | |
for j in itertools.permutations(nums): | |
if calc(i, list(j)) == 24: | |
a, b = list(map(signs_to_txt, i)), j[::-1] | |
print(pretty(a, b)) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment