python - 如何计算24?

标签 python algorithm

我写了一个 python 脚本试图解决“计算 24”问题,该问题源于一个游戏,从一副纸牌中抽取 4 张纸牌并尝试使用 +、-、* 和/获得值 24。

代码是有效的,只是它有很多重复,例如,我输入 2, 3, 4, 5 得到 24 的值,它会找到并打印 2*(3 + 4 + 5) 是24,但它还会打印 2*(5 + 4 + 3)、2*(5 + 3 + 4) 等,同时它会找到 4*(3 + 5 - 2),它还会打印 4* (5 + 3 - 2)。谁能给我一些关于如何删除重复答案的提示?

代码如下:

def calc(oprands, result) :
    ret=[]
    if len(oprands)==1 :
        if oprands[0]!=result :
            return ret
        else :
            ret.append(str(oprands[0]))
            return ret
    for idx, x in enumerate(oprands) :
        if x in oprands[0:idx] :
            continue
        remaining=oprands[0:idx]+oprands[idx+1:]
        temp = calc(remaining, result-x)         # try addition
        for s in temp :
            ret.append(str(x) + ' + ' + s)
        if(result%x == 0) :                      # try multiplication
            temp = calc(remaining, result/x)
            for s in temp :
                ret.append(str(x) + ' * (' + s + ')')
        temp = calc(remaining, result+x)          # try subtraction
        for s in temp :
            ret.append(s + ' - ' + str(x))
        temp = calc(remaining, x-result)
        for s in temp :
            ret.append(str(x) + ' - (' + s + ')')
        temp = calc(remaining, result*x)          # try division
        for s in temp :
            ret.append('(' + s + ') / ' + str(x))
        if result!=0 and x%result==0 and x/result!=0 :
            temp = calc(remaining, x/result)
            for s in temp :
                ret.append(str(x) + ' / ' + '(' +s +')')
    return ret

if __name__ == '__main__' :
    nums = raw_input("Please input numbers seperated by space: ")
    rslt = int(raw_input("Please input result: "))
    oprds = map(int, nums.split(' '))
    rr = calc(oprds, rslt)
    for s in rr :
        print s
    print 'calculate {0} from {1}, there are altogether {2} solutions.'.format(rslt, oprds, len(rr))

最佳答案

计算 24 是一个有趣且具有挑战性的游戏。正如其他用户在评论中指出的那样,很难创建一个没有任何缺陷的解决方案。

你可以研究 Rosetta Code (spoiler alert)实现并将其与您的解决方案进行比较。

关于python - 如何计算24?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25199131/

相关文章:

c++ - 在 C++ 中找到与方程匹配的最小整数

algorithm - 随机打乱相同元素的排序比较方法

python - 将日期转换为 unix 时间戳时增加一小时

python - 为 Python 2 解压打印列表

python - 无法在 Ubuntu 14.04 上升级 pip 1.5.4 - InsecurePlatformWarning : A true SSLContext object is not available

c# - 检测数据的重大变化

Bron-Kerbosch算法的C#实现

algorithm - 图中最长的圆

python - Pandas - 从分类列创建 bool 列

Python退出所有函数并停止执行