怎么算24?

时间:2014-08-08 08:31:10

标签: python algorithm

我写了一个python脚本试图解决'计算24'问题,这个问题起源于一个游戏,从一副牌中抽取4张牌并尝试使用+, - ,*和/来获得值24。 / p>

代码正在工作,只是它有很多重复,例如,我输入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 个答案:

答案 0 :(得分:3)

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

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

相关问题