我写了一个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))
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1024 次 |
最近记录: |