how to calculate 24?
I wrote a python script trying to solve the 'calculate 24' problem, which originated from a game, drawing 4 cards from a deck of cards and try to get the value 24 using +,-, *, and /.
The code is working, only that it have many duplications, for example, I input 2, 3, 4, 5 to get the value of 24, it will find and print that 2*(3 + 4 + 5) is 24, but it will also print 2*(5 + 4 + 3), 2*(5 + 3 + 4), etc., while it will find 4*(3 + 5 - 2), it will also print 4*(5 + 3 - 2). Could anyone please give me some hints on how to remove duplicated answers?
The code is as follows:
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))
Calculate 24 is an interesting and challenging game. As other users pointed out in the comments, it's difficult to create a solution that doesn't present any flaw.
You could study the Rosetta Code (spoiler alert) implementation and compare it to your solution.
链接地址: http://www.djcxy.com/p/22368.html上一篇: 如何在Swift中编写任何(s:SequenceType)
下一篇: 如何计算24?