递归-算24

给出4个小于10个正整数,你可以使用加减乘除4种运算以及括号把这4个数连接起来得到一个表达式。现在的问题是,是否存在一种方式使得得到的表达式的结果等于24。

这里加减乘除以及括号的运算结果和运算的优先级跟我们平常的定义一致(这里的除法定义是实数除法)。
比如,对于5,5,5,1,我们知道5 * (5 – 1 / 5) = 24,因此可以得到24。又比如,对于1,1,4,2,我们怎么都不能得到24。

输入:输入数据包括多行,每行给出一组测试数据,包括4个小于10个正整数。最后一组测试数据中包括4个0,表示输入的结束,这组数据不用处理。

输出:对于每一组测试数据,输出一行,如果可以得到24,输出“YES”;否则,输出“NO”。

样例输入
5 5 5 1
1 1 4 2
0 0 0 0

样例输出
YES
NO

解题思路:n个数算24,必有两个数要先算。这两个数算的结果,和剩余n-2个数,就构成了n-1个数求24的问题枚举先算的两个数,以及这两个数的运算方式。

针对这题,给了两种解题代码。

python第一种代码:

"""
解题思路:
n个数算24,必有两个数要先算。这两个数算的结果,和剩余n-2个数,就
构成了n-1个数求24的问题
枚举先算的两个数,遍历递归调用以及这两个数的运算方式。

fruits = ['banana', 'apple',  'mango']
for index in range(1,3):
    print(index)
    print('当前水果 :', fruits[index])
"""

import math
import sys

#sys.setrecursionlimit(1000000)
#定义一个极小的常量,用于浮点数的比较是否相等
#计算10的负7次方
EPS = 1e-06

#存储需要计算的数,初始是4个,然后会逐渐减少
#dataList = []

#判断传入x值是否是0
def isZero(x):
    #print(x)
    if ( math.fabs(x) <= EPS):
        return True
    else:
        return False

def count24(dataList,n):
    #global dataList
    #临时存储的列表
    tempDataList = [0] * 4
    #当计算到最后一个数,其值等于24时,说明能成功
    if (n == 1):
        if (isZero(dataList[0]-24)):
            return True
        else:
            return False
    #for i,ii in enumerate(dataList):
    for i in range(n-1):
        #for j,jj in enumerate(dataList[i+1:],1):
        for j in range(i+1,n):
            #还剩下m个数, m = n - 2
            m = 0
            #for k,kk in enumerate(dataList):
            for k in range(n):
                if ( k!=i and k!=j ):
                    #把剩下的数存入临时的列表
                    tempDataList[m] = dataList[k]
                    m += 1

            tempDataList[m] = dataList[i] + dataList[j]
            if (count24(tempDataList,m + 1)):
                return True
            tempDataList[m] = dataList[i] - dataList[j]
            if (count24(tempDataList, m + 1)):
                return True
            tempDataList[m] = dataList[j] - dataList[i]
            if (count24(tempDataList, m + 1)):
                return True
            tempDataList[m] = dataList[i] * dataList[j]
            if (count24(tempDataList, m + 1)):
                return True
            if ( not isZero(round(dataList[i],6))):
                tempDataList[m] = round(dataList[j]/dataList[i],6)
                if (count24(tempDataList, m + 1)):
                    return True
            if ( not isZero(round(dataList[j],6))):
                tempDataList[m] = round(dataList[i]/dataList[j],6)
                if (count24(tempDataList, m + 1)):
                    return True
    return False

def main():
    #print(math.pow(10,-7))
    #global dataList
    dataList = list(map(int,input("请输入需要计算的4个整数,空格间隔:").split(" ")))
    if count24(dataList,4):
        print("Yes!")
    else:
        print("No!")

if __name__ == "__main__":
    main()

第二种实现代码:

"""
解题思路:
n个数算24,必有两个数要先算。这两个数算的结果,和剩余n-2个数,就
构成了n-1个数求24的问题
枚举先算的两个数,遍历递归调用以及这两个数的运算方式。
"""

import math

#sys.setrecursionlimit(1000000)

#定义一个极小的常量,用于浮点数的比较是否相等
#计算10的负7次方
EPS = 1e-07

#判断传入x值是否是0
def isZero(x):
    #print(x)
    if ( math.fabs(x) <= EPS):
        return True
    else:
        return False

def count24(dataList,n):

    #当计算到最后一个数,其值等于24时,说明能成功
    if (n == 1):
        if (isZero(dataList[0]-24)):
            return True
        else:
            return False
    i,j = 0,0
    # 临时存储的列表
    tempDataList = [0] * 4
    while i < n-1:
        j = i + 1
        while j < n:
            #把剩下的n-2个数放入临时列表中
            k,m = 0,0
            while k < n:
                if (i != k and j != k):
                    tempDataList[m] = dataList[k]
                    m = m + 1
                k += 1
            # 把剩下的n-2个数放入临时列表中
            tempDataList[m] = dataList[i] + dataList[j]
            if (count24(tempDataList, m + 1)):
                return True
            tempDataList[m] = dataList[i] - dataList[j]
            if (count24(tempDataList, m + 1)):
                return True
            tempDataList[m] = dataList[j] - dataList[i]
            if (count24(tempDataList, m + 1)):
                return True
            tempDataList[m] = dataList[j] * dataList[i]
            if (count24(tempDataList, m + 1)):
                return True
            if (not isZero(round(dataList[i], 6))):
                tempDataList[m] = round(dataList[j] / dataList[i],6)
                if (count24(tempDataList, m + 1)):
                    return True
            if (not isZero(round(dataList[j],6))):
                tempDataList[m] = round(dataList[i] / dataList[j],6)
                if (count24(tempDataList, m + 1)):
                    return True

            j = j + 1
        i = i +1
    return False

def main():
    #print(math.pow(10,-7))
    #global dataList
    dataList = list(map(int,input("请输入需要计算的4个整数,空格间隔:").split(" ")))
    if count24(dataList,4):
        print("Yes!")
    else:
        print("No!")

if __name__ == "__main__":
    main()
原文地址:https://www.cnblogs.com/an-wl/p/12435005.html