思路:
1、对4张牌进行全排序,并输出列表
2、分别对排序进行计算尝试,采用穷举方式
3、返回结果
除了用递归生成器进行数组全排序外,也用模块from itertools
import
permutations,进行全排序。
1 #输出算式运算顺序从左至右运算,不需要括号确定优先级。 2 3 #列举所有排序方式,比如 1234,1324...... 4 def relist(a):#用递归生成器返回不重复顺序的列表 5 if len(a)==1: 6 yield a 7 for i in range(len(a)): 8 for j in relist(a[:i]+a[i+1:]): 9 #print( a[i],j) 10 yield [a[i]]+j 12 def twentyfour(a):#采用多重循环对数组a所有计算方式穷举。 13 operator=['+','-','*','/'] 14 for i in operator: 15 for j in operator: 16 for n in operator: 17 if dop[i](dop[j](dop[n](a[0],a[1]),a[2]),a[3])==24: 18 return a,n,j,i 19 import operator 20 dop={'+':operator.add,'-':operator.sub,'*':operator.mul,'/':operator.truediv} 21 d={'J':11,'Q':12,'K':13,'A':1} 22 a=input().split() 23 b=a.copy() 24 flag=0 25 for k,i in enumerate(a): 26 if i.isdigit(): 27 a[k]=int(i) 28 elif i in d: 29 a[k]=d[i] 30 else: 31 print("ERROR") 32 flag=1 33 #用flag使当输出”ERROR"不再进行后面运算,用flag1,输出NONE. 34 if flag==0: 35 flag1=0 36 for i in relist(a): 37 #print(i) 38 new=[] 39 if twentyfour(i): 40 temp,n1,n2,n3=twentyfour(i) 41 for i in temp: 42 for k,j in enumerate(a): 43 if i==j: #查表打印特殊字符JQKA 44 new.append(b[k]) 45 break 46 tem=str(new[0])+n1+str(new[1])+n2+str(new[2])+n3+str(new[3]) 47 print(tem) 48 flag1=1 49 break 50 if flag1==0: 51 print('NONE')
标签:24,生成器,operator,flag1,new,print,穷举 From: https://www.cnblogs.com/tanyuanqing/p/17366708.html