如何计算24?

7 投票
1 回答
2124 浏览
提问于 2025-04-18 16:30

我写了一个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))

1 个回答

3

计算24是一个有趣且具有挑战性的游戏。正如其他用户在评论中提到的,想要找到一个没有任何缺陷的解决方案是很困难的。

你可以研究一下Rosetta Code(剧透警告)上的实现,并将其与你自己的解决方案进行比较。

撰写回答