题解 | 24点8层循环暴力枚举

nums = input().split()

nums[0] = nums[0]+"e"
nums[1] = nums[1]+"f"
nums[2] = nums[2]+"g"
nums[3] = nums[3]+"h"
# nums = ["3e", "9f", "3g", "4h"]


opts = ["+", "-", "*", "/"]

res = []

templates = [
    "((a.b)#c)@d",
    "(a.(b#c))@d",
    "a.((b#c)@d)",
    "(a.b)#(c@d)",
    "a.(b#(c@d))",
]

l = 0


def has24(nums):
    for i in nums:
        for j in nums:
            if j == i:
                continue
            for k in nums:
                if j == k or i == k:
                    continue
                for h in nums:
                    if i == h or j == h or k == h:
                        continue
                    for t in templates:
                        for o in opts:
                            for p in opts:
                                for q in opts:
                                    item = t\
                                        .replace(".", o)\
                                        .replace("#", p)\
                                        .replace("@", q)\
                                        .replace("a", i)\
                                        .replace("b", j)\
                                        .replace("c", k)\
                                        .replace("d", h)\
                                        .replace("e", '')\
                                        .replace("f", '')\
                                        .replace("g", '')\
                                        .replace("h", '')
                                    try:
                                        if (abs(eval(item) - 24)<1e-6):
                                            # print(item)
                                            return "true"
                                    except:
                                        # print(item)
                                        continue
    return "false"


print(has24(nums))

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务