题解 | #24点运算#
24点运算
https://www.nowcoder.com/practice/7e124483271e4c979a82eb2956544f9d
from re import T import sys porker = {'J':'11','Q':'12','K':'13','A':'1'} def check(numlist, res, sym): if len(numlist)==0: if res == 24: return True, sym else: return False, sym else: allflag = False for i in range(len(numlist)): left = numlist[:i]+numlist[i+1:] v = numlist[i] if res==0: allflag, sym = check(left, int(v), v) else: flagadd, addsym = check(left, res+int(v), sym+'+'+v) flagsub, subsym = check(left, res-int(v), sym+'-'+v) flagmut, mutsym = check(left, res*int(v), sym+'*'+v) flagdiv, divsym = check(left, res/int(v), sym+'/'+v) flag = flagadd or flagsub or flagmut or flagdiv allflag = allflag or flag if flagadd: sym = addsym if flagsub: sym = subsym if flagmut: sym = mutsym if flagdiv: sym = divsym if allflag: break return allflag, sym for line in sys.stdin: a = line.split() error = False for j in range(len(a)): this = a[j] if not this.isdigit(): if this in porker.keys(): a[j] = porker[this] else: error = True break if error: print('ERROR') else: do, sym = check(a,0,'') if do: sym = sym.replace('11','J') sym = sym.replace('12','Q') sym = sym.replace('13','K') sym = sym.replace('1','A') print(sym) else: print('NONE')