24点是一种益智游戏,任意给出4张扑克牌(不含大小王,J Q K A所代表的值分别为11, 12, 13, 1),可以有重复的数字。对这4张牌所代表的值进行加减乘除运算,不可改变数字的位置,但可使用括号改变运算顺序,最终使得表达式的值为24 。
python实现:
from operator import add,sub,mul,div
l=[]
def s(a,c,d,cl,cr):
if len(a)==7 and abs(a[6]-24)<1e-5 and c[6] not in l:
l.append(c[6])
print "%d) %s"%(len(l),c[6])
for i in range(len(a)):
if c[i]!='':
for j in range(len(a)):
if c[j]!='':
for op in range(4):
if i!=j and (op!=3 or a[j]!=0) and\
not (op%2==0 and (d[i]==op+1 or d[j]==op+1)) and\
not (op%2==0 and d[i]==op and d[j]/2!=op/2 and cr[i]>c[j]) and\
not (op%2==0 and d[i]!=op and d[j]!=4 and c[i]>cl[j]) and\
not (op%2==0 and d[i]==op and d[j]/2==op/2 and cr[i]>cl[j]) and\
not (op%2==0 and d[i]!=op and d[j]/2!=op/2 and c[i]>c[j]) and\
not (op%2==1 and d[i]==op and cr[i]>c[j]) and\
not (op%2==1 and d[j]/2==op/2) and\
not (op==3 and a[j]==1) and\
not (op==2 and a[i]<0 and a[j]<0):
ci=(op>=2 and d[i]<2) and ('('+c[i]+')') or c[i]
cj=(op>=2 and d[j]<2) and ('('+c[j]+')') or c[j]
c0=c+[ci+('+-*/')[op]+cj];
c0[i]=''; c0[j]=''
s(a+[([add,sub,mul,div][op])(a[i],a[j])],c0,d+[op],\
cl+[d[i]!=4 and cl[i] or c[i]],cr+[d[j]!=4 and cr[j] or c[j]])
if __name__=='__main__':
c=[input('Card '+str(i+1)+':') for i in range(4)]
s([j*1.0 for j in c],[str(j) for j in c],[4,4,4,4],['','','',''],['','','',''])