• 杂谈:玩玩24点
    • 0. 引言
    • 1. 代码实现 & 评测
    • 2. 一点后续

0. 引言

故事起源于一个寂寞的晚上,一个人无聊就随手拿出了一副扑克牌,开始玩24点,然而悲剧的是,完了好几轮,每一轮平均都有2-3组24点算不出来,顿时怒火攻心。不就是4个数字吗?排列组合也就那么点情况,居然还能搞不定,简至了,为自己的智商感觉到了深深的悲哀。。。

emmmm。。。

排列组合也就那么几种情况?!拿自己写个脚本不就完事了吗?于是就随手写了个24点的作弊脚本,直接机算24点。。。

发现自己真是个小机灵

1. 代码实现 & 评测

如前所述,24点这个游戏本来也挺简单的,总共也就只有4个数字,允许的操作符号也就加减乘除4种,因此,实现起来也就只要遍历一下就行了。本质而言没啥特别的。

直接给出下述代码实现如下:

from itertools import permutations, product
def twenty_four_point(nums):
    print("inputs : {}".format(nums))
    for a, b, c, d in permutations(nums):
        for op1, op2, op3 in product("+-*/", repeat=3):
            y = eval("(({}{}{}){}{}){}{}".format(a, op1, b, op2, c, op3, d))
            if y == 24:
                print("answer : (({}{}{}){}{}){}{}".format(a, op1, b, op2, c, op3, d))
                return True
            try:
                y = eval("({}{}{}){}({}{}{})".format(a, op1, b, op2, c, op3, d))
                if y == 24:
                    print("answer : ({}{}{}){}({}{}{})".format(a, op1, b, op2, c, op3, d))
                    return True
            except:
                continue
    print("oops, there is no answer")
    return False

评测一些结果得到:

# 1
inputs : [2, 8, 5, 7]
answer : ((2*5)-7)*8
# 2
inputs : [2, 3, 3, 4]
oops, there is no answer

测试结果整体上还是让人满意的!

2. 一点后续

Two thousands years later…

话说,我写这个脚本是为了帮助计算一些比较难的24点的吧,但是,但是,但是,为毛发现自从写了这个脚本,反而更加不会算24点了啊?!!!

唉,果然有了作弊工具之后下意识地就开始偷懒了,这真是一个悲伤的故事。。。

本文地址:https://blog.csdn.net/codename_cys/article/details/110711651