python-24点智取游戏

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],['','','',''],['','','','']) 
  



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值