科技行者

行者学院 转型私董会 科技行者专题报道 网红大战科技行者

知识库

知识库 安全导航

至顶网软件频道应用软件 python编的算24的程序!

python编的算24的程序!

  • 扫一扫
    分享文章到微信

  • 扫一扫
    关注官方公众号
    至顶头条

python编的算24的程序!

作者: jamesfangjing 来源:CSDN 2008年5月27日

关键字: 程序 python 软件

  • 评论
  • 分享微博
  • 分享邮件
 

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 !"

    • 评论
    • 分享微博
    • 分享邮件
    邮件订阅

    如果您非常迫切的想了解IT领域最新产品与技术信息,那么订阅至顶网技术邮件将是您的最佳途径之一。

    重磅专题
    往期文章
    最新文章