题解 | #24点游戏算法#

24点游戏算法

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

import sys

nums = list(map(int, input().split()))
op = ['+', '-', '*', '/']

def quan(nums, res):  # 全排列
    n = len(nums)
    def tool(first):
        if first == n:
            res.append(nums[:])
            return
        s = set()
        for i in range(first, n):
            if nums[i] not in s:
                s.add(nums[i])
            else:
                continue

            nums[i], nums[first] = nums[first], nums[i]
            tool(first + 1)
            nums[i], nums[first] = nums[first], nums[i]
    tool(0)

def func(a, b, op):
    if op == '+':
        return a + b
    elif op == '-':
        return a - b
    elif op == '*':
        return a * b
    elif op == '/':
        return a / b

res = []
quan(nums, res)
# print(res)
for nums in res:  # 枚举
    for i in range(4):
        for j in range(4):
            for k in range(4):
                if (func(func(func(nums[0], nums[1], op[i]), nums[2], op[j]), nums[3], op[k]) == 24):
                    print('true')
                    sys.exit()

print('false')
            
                

全部评论

相关推荐

专心打鱼:互联网搬运工,贴子都要偷
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务