24点运算
24点运算
http://www.nowcoder.com/questionTerminal/7e124483271e4c979a82eb2956544f9d
参考了高赞答案中函数的用法
python使用itertools.permutations给出全排列,用eval计算字符串表示的算式值
- 将四个输入的数字全排列,共有4!= 24种情况
- 四个数中间有三个运算符,每个运算符有4种可能,共种可能情况
需要遍历种情况。每种情况的运算顺序为:从左至右依次计算。比如:
import itertools def tf(): while True: try: val_dict = {'A':'1','J':'11','Q':'12','K':'13'} mapOp={'0':'+','1':'-','2':'*','3':'/'} s = input().split() for i in s: if (i == 'joker') or (i == 'JOKER'): print("ERROR") return new_s = [] for d in s: if d in val_dict: new_s = new_s + [val_dict[d]] else: new_s = new_s + [d] for val in itertools.permutations(range(4),4): for i1,i2,i3 in itertools.product(map(str,range(4)),repeat=3): tems = '(('+new_s[val[0]]+mapOp[i1]+new_s[val[1]]+')'+mapOp[i2]+new_s[val[2]]+')'+mapOp[i3]+new_s[val[3]] if eval(tems)==24: outs = s[val[0]]+mapOp[i1]+s[val[1]]+mapOp[i2]+s[val[2]]+mapOp[i3]+s[val[3]] print(outs) return print("NONE") except: break if __name__=='__main__': tf()