我编写了一个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))发布于 2014-08-08 08:54:45
计算24是一项有趣且具有挑战性的游戏。正如其他用户在评论中指出的那样,很难创建一个没有任何缺陷的解决方案。
您可以研究罗塞塔代码(扰流板警报)实现并将其与解决方案进行比较。
https://stackoverflow.com/questions/25199131
复制相似问题