题解 | #24点运算#
24点运算
https://www.nowcoder.com/practice/7e124483271e4c979a82eb2956544f9d?tpId=37&tqId=21312&rp=1&ru=/exam/oj/ta&qru=/exam/oj/ta&sourceUrl=%2Fexam%2Foj%2Fta%3Fpage%3D2%26tpId%3D37%26type%3D37&difficulty=undefined&judgeStatus=undefined&tags=&title=
import sys import itertools #from numpy import product s = input().split() def compute24(s): #包含大小王的情况,不处理,直接输出ERROR if "joker" in s: print("ERROR") return elif "JOKER" in s: print("ERROR") return #替换J QKA中的值 for i in range(len(s)): if s[i]=="J": s[i]=11 elif s[i]=="Q": s[i]=12 elif s[i]=="K": s[i]=13 elif s[i]=="A": s[i]=1 operations=["+","-","*","/"] operate_number=list(map(lambda x:int(x),s)) #利用笛卡尔积生成操作种类 L1=[ i for i in itertools.product(operations,repeat=3)] #利用Proxxx生成操作数的全排列 L2=[i for i in itertools.permutations(operate_number,4)] L2=list(set(L2)) #将操作数和操作符拼接,中间需要用括号保证先计算前俩位,然后用结果与第三位计算,最后和第四位计算 #即((A operate B)operate c) operate D,所以我先添加了2个括号,然后在第二个操作数和第三个操作数后添加了一个括号各, j=0 L4=[] #遍历操作数 for x in L2: #遍历操作符号 for y in L1: j=0 L3=[] L3.append("((") for i in range(len(x)): L3.append(x[i]) #当添加第二或者第三个操作数的时候添加完记得加括号 if i==1 or i==2: L3.append(")") #j<2说名添加完了操作符号,只需要再添加一个操作数就可以退出for循环本次的, if j <=2: L3.append(y[j]) j+=1 L4.append(L3) MathRepresenttions=[] i=0 for i in L4: i=list(map(lambda x: str(x),i)) expression = "".join(i) MathRepresenttions.append(expression) x=0 L5=[] for x in MathRepresenttions: result =eval(x) if result==24: L5.append(x) #将之前替换的替换回来输出 if len(L5)==0: print("NONE") else: for i in L5: L6=[] if "13" in i: i=i.replace("13","K") if "12" in i: i=i.replace("12","Q") if "11" in i: i=i.replace("11","J") if "1" in i: i=i.replace("1","A") #去掉括号,输出的时候不用括号,从左到右计算 for j in i: if j =="(" or j==")": pass else: L6.append(j) print("".join(L6)) return compute24(s)