python编的算24的程序!

类别:软件工程 点击:0 评论:0 推荐:

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的领悟,高手指点一下!

本文地址:http://com.8s8s.com/it/it32956.htm