python编的算24的程序!

王朝other·作者佚名  2006-01-09
窄屏简体版  字體: |||超大  

def twoNum(num1,num2,sign): #computer the result of two numbers

if sign=='/':

if num2!=0:

return num1/num2

else:

return 50000

else:

return eval(str(num1)+sign+str(num2))

def show(num1,num2,sign): #show the result of two numbers

print "%.1f %s %.1f = " % (num1,sign,num2),

def c24(numList):

sign=('+','-','*','/')

length=len(numList)

tempList=range(length-1) #get the result of two numbers, so the length minus 1

if length==2: #when there are only 2 numbers, computer directly!

n1=numList[0]

n2=numList[1]

for s in sign:

result1=twoNum(n1,n2,s)

result2=twoNum(n2,n1,s)

if result1==24.0:

show(n1,n2,s)

print "%.1f" % result1

return 1

elif result2==24.0:

show(n2,n1,s)

print "%.1f" % result2

return 1

return 0

else:

for i in range(length): #view all the possible collection of numbers

n1=numList[i]

for j in range(length):

if j!=i:

n2=numList[j]

temp=1

for k in range(length): #get the left numbers

if k!=i and k!=j:

tempList[temp]=numList[k]

temp+=1

for s in sign:

result=twoNum(n1,n2,s)

tempList[0]=result #the result is always put on position 0

if c24(tempList): #recurrent the number List

show(n1,n2,s)

print "%.1f" % result

return 1

return 0

numTuple=input("Please input 4 numbers to computer 24:(use ',' to divide them)")

numList=[float(i) for i in numTuple]

print "You input is : ", numList

if not c24(numList):

print "It is a mission impossible !"

程序不长,应该好懂,自己感觉是写的很烂的,还没摆脱c和c++的风格,欠缺python的领悟,高手指点一下!

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航