实例介绍
【实例简介】
用Python做的24点游戏
【实例截图】
【核心代码】
#!/usr/bin/env python
#--coding:utf-8--
import string,time,argparse,math
import traceback
from multiprocessing import Process, Lock,Pool
__author__="CHANG Tiangen"
__date__="20121102"
__copyright__="Copyright 2012, a game for fun"
__license__="GPL"
__version__="0.1"
__email__="changtiangen@gmail.com"
__status__="Prototype"
__credits__=[]
def create_help_parser():
epilog_string="Any bug is welcome reported to changtiangen@gmail.com"
description_string='The programe is going to caculate whether the line integer vector in the data file can obtain 24 by combination of \' \',\'-\',\'*\',\'/\'.'
parser = argparse.ArgumentParser(description=description_string,epilog=epilog_string)
parser.add_argument('-f', '--file', dest='fnIn', help='input file name.', required=True)
parser.add_argument('-o', '--output', dest='fnOut', help='output file name, default is pointSol.txt',default='pointSol.txt')
parser.add_argument('-p','--Process Number',type=int,dest='process_number',required=True,help='Input the process number need for the programme, no default.')
op=parser.parse_args()
return op
def makeDictionary(rawData=[]):
'''
make a dictionary for raw input data [a,b,c,...], the dictionary is like[('a',a),('b',b),('c',c),...]
'''
Data=zip(map(str,rawData),rawData)
return Data
def rerange(dataForRerange=[]):
'''
rerange the dictionaried data, i.e. the full permutation of the data
'''
rerangedData=[]
for i in range(len(dataForRerange)):
for j in range(i 1,len(dataForRerange)):
tempData=dataForRerange[:]
tempData[0],tempData[i]=tempData[i],tempData[0]
tempData[1],tempData[j]=tempData[j],tempData[1]
if tempData not in rerangedData:
rerangedData.append(tempData)
return rerangedData
def calculate(data=[]):
'''
calculate the " , - ,*,/" result between data[0][1] and data[1][1] and replace data[0],data[1] with it.
'''
result=[]
temp=[('(' data[0][0] ' ' data[1][0] ')',data[0][1] data[1][1])] data[2:]
if temp not in result:
result.append(temp)
temp=[('(' data[0][0] '*' data[1][0] ')',data[0][1]*data[1][1])] data[2:]
if temp not in result:
result.append(temp)
if (data[1][1]>0.00001)|(data[1][1]<-0.00001) :
temp=[('(' data[0][0] '/' data[1][0] ')',float(data[0][1])/data[1][1])] data[2:]
if temp not in result:
result.append(temp)
if (data[0][1]>0.00001)|(data[0][1]<-0.00001) :
temp=[('(' data[1][0] '/' data[0][0] ')',float(data[1][1])/data[0][1])] data[2:]
if temp not in result:
result.append(temp)
if data[0][1]>=data[1][1]:
temp=[('(' data[0][0] '-' data[1][0] ')',data[0][1]-data[1][1])] data[2:]
if temp not in result:
result.append(temp)
else:
temp=[('(' data[1][0] '-' data[0][0] ')',data[1][1]-data[0][1])] data[2:]
if temp not in result:
result.append(temp)
return result
def findSolution(final=[]):
'''
if result equals to 24, is a solution
'''
solution=[]
if (final[0][1]<=24.0001)&(final[0][1]>=23.9999):
solution=final[0][0]
if len(solution)>0:
return solution
def merge(lineStr='',pool=0,fileOut='output.txt'):
'''
merge all the function above and write the final result to file
'''
solution=open(fileOut,'a')
solution.write(lineStr ':' '\n')
p=Pool(pool)#multiprocessing
row = lineStr.split()
rowData=map(string.atoi,row)# turn string element in row to int type
Data=makeDictionary(rawData=rowData)
Data=[Data]
if len(Data)>0:
while len(Data[0])>1:#if len(Data[0])=1, that means we get the final result of all permutation, e.g. Data[0]=['(((a b)-c)/d)',(((a b)-c)/d))]
CalculateData=map(rerange,Data)
CalculateData=[j for i in CalculateData for j in i]#reduce the dimension of 'CalculateData'
result=p.map(calculate,CalculateData)
Data=[j for i in result for j in i ]
if len(Data[0])==1:
rawSolution=p.map(findSolution,Data)
rawSolution=list(set(rawSolution))#delete the identical pattern in raw solution
for i in range(len(rawSolution)):
if rawSolution[i]!=None:
solution.write(rawSolution[i] '\n')#write result to file
solution.close()
def main_process():
'''
function for all the progress
'''
op=create_help_parser()
tempF=open(op.fnOut,'w')
tempF.close()#remove all the exist data in the output file
allData=open(op.fnIn,'r')
for line in allData:
line=line.strip()
Process(target=merge,args=(line,op.process_number,op.fnOut)).start()
if __name__=='__main__':
start_time=time.clock()
main_process()
elapsed=time.clock()-start_time
print "The process is done"
print "Time used:",elapsed
标签: 游戏
网友评论
小贴士
感谢您为本站写下的评论,您的评论对其它用户来说具有重要的参考价值,所以请认真填写。
- 类似“顶”、“沙发”之类没有营养的文字,对勤劳贡献的楼主来说是令人沮丧的反馈信息。
- 相信您也不想看到一排文字/表情墙,所以请不要反馈意义不大的重复字符,也请尽量不要纯表情的回复。
- 提问之前请再仔细看一遍楼主的说明,或许是您遗漏了。
- 请勿到处挖坑绊人、招贴广告。既占空间让人厌烦,又没人会搭理,于人于己都无利。
关于好例子网
本站旨在为广大IT学习爱好者提供一个非营利性互相学习交流分享平台。本站所有资源都可以被免费获取学习研究。本站资源来自网友分享,对搜索内容的合法性不具有预见性、识别性、控制性,仅供学习研究,请务必在下载后24小时内给予删除,不得用于其他任何用途,否则后果自负。基于互联网的特殊性,平台无法对用户传输的作品、信息、内容的权属或合法性、安全性、合规性、真实性、科学性、完整权、有效性等进行实质审查;无论平台是否已进行审查,用户均应自行承担因其传输的作品、信息、内容而可能或已经产生的侵权或权属纠纷等法律责任。本站所有资源不代表本站的观点或立场,基于网友分享,根据中国法律《信息网络传播权保护条例》第二十二与二十三条之规定,若资源存在侵权或相关问题请联系本站客服人员,点此联系我们。关于更多版权及免责申明参见 版权及免责申明


支持(0) 盖楼(回复)
支持(0) 盖楼(回复)
支持(0) 盖楼(回复)