题解 | #24点游戏算法#

24点游戏算法

https://www.nowcoder.com/practice/fbc417f314f745b1978fc751a54ac8cb

import itertools


def fun(arr, y):

    # 前面的结果与后一个数加减乘除的可能
    res = []
    for x in arr:
        res.append(x)
        res.append(y)
        res.append(x + y)
        res.append(x - y)
        res.append(x * y)
        if y != 0:
            res.append(x / y)
    return res


while True:
    
    try:
        num_list = [int(i) for i in input().split()]
        
        # 存放所有加减乘除的可能
        result_list = []
        # 所有数字排列的顺序都考虑进去
        for i in range(len(list(itertools.permutations(num_list)))):
            a, b, c, d = list(itertools.permutations(num_list))[i]
            list1 = fun([a], b)
            list2 = fun(list1, c)
            list3 = fun(list2, d)
            result_list.extend(list3)
			#考虑了4个数先两两计算再进行运算的情况
            list4 = fun([c], d)
            for i in range(len(list4)):
                list5 = fun(list1, list4[i])
                result_list.extend(list5)
        # 只要24在所有的结果中就满足条件
        if 24 in result_list:
            print('true')
        else:
            print('false')
        
    except:
        break

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务