您的位置:首页 > 编程语言 > Python开发

Python算24点

2016-02-13 20:47 666 查看

    穷举法算24点

  之前闲着无聊看了到知乎推荐的一个qq群里面的python程序设计题,大概意思是对于A~K 相当于1-13对于抽到的4个数进行运算,数字顺序不能打乱,进行加减乘除,允许添加括号,计算出所有的24点的可能

无聊使用最笨的方法穷举出来了,没有任何算法,计算输出好慢

from collections import OrderedDict
#对于定序数字计算24点,可以用括号改变计算顺序
def insertr(num,lst,s):
lenth=len(lst)
if num==lenth:
lst.append(s)
else:
lst.insert(num+1,s)

def getopera(s):
#获取字符串中操作符的位置
t=[]
for k in range(len(s)):
if s[k] in ['+','-','*','/']:
t.append(k)
return t

def kuohao(num,lst):
#在操作元两边添加括号
t=getopera(lst)
pos=t[num] #获取数组中第num个opera的位置
lenth=len(lst)
if lst[pos-1]==')' : #判断左操作元是否为(a*d)形式and (lst[pos]=="+" or lst[pos]=='-)')
insertr(pos+1,lst,')')
for le in reversed(range(pos)):
if lst[le]=='(':
lst.insert(le,'(')
break
elif lst[pos+1]=='(':# and (lst[pos]=="+" or lst[pos]=='-)')
lst.insert(pos-1,'(')
t=getopera(lst)
pos=t[num] #获取数组中第num个opera的位置
lenth=len(lst)
for le in range(pos+1,lenth):
if lst[le]==')':
insertr(le,lst,')')
break
else:
lst.insert(pos-1,'(')
insertr(pos+1+1,lst,')')

def list2str(lst):
t=''
for s in lst:
t+=str(s)
return t
def listchange(lst):#删除表达式中不必要的list
pass

def cal24(s):
ans=[]
a,b,c,d=list(map(str,s))
opera=['+','-','*','/']
for op1 in opera:
for op2 in opera:
for op3 in opera:
for i in range(3):
s=[a,op1,b,op2,c,op3,d]
kuohao(i,s)
for j in range(3):
k=s.copy()
if j==i:
pass
else:
kuohao(j,k)
exp=list2str(k)
try:  #使用try可以避免eval 除数为0的错误
if eval(exp)==24:#将string转化为exp进行计算
ans.append(exp+'\n')
except:
pass
return ans

'''
s=['(',12,'+',4,')','*',3,'/',5]
print(getopera(s))
kuohao(2,s)
k=list2str(s)
print(k)
print(eval(k))
#lst=[10,9,5,1]
lst=[8,10,6,6]
t=cal24(lst)
'''
#构建扑克牌字典
poker=list(map(str,range(2,11)))
poker.insert(0,'A')
poker+=['J','Q','K']
number=list(map(str,range(1,14)))
dict1=OrderedDict(zip(poker,number))

with open('24_data.txt','a') as f:
for v1,k1 in dict1.items():
for v2,k2 in dict1.items():
for v3,k3 in dict1.items():
for v4,k4 in dict1.items():
s=cal24([k1,k2,k3,k4])
f.write("====%s,%s,%s,%s\n"%(v1,v2,v3,v4))
if len(s)==0:
f.write('Impossible\n')
else:
f.writelines(s)


跑完用了几分钟。。。。。。效率好低 无语
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python 算24点