算24点

简单的 bruce force, 算法如下, 未能证明其正确性.
给定一组数据 (1,2,3,4) 和 操作符 (-,+,*)
则有两种可能结果

((1-2) + 3) * 4
((1-2) * (3+4))

再通过排列 给定的数据和操作符 来重复上述操作

请大家指点指点
- 代码语法等方面如何改进
- 算法上是否正确、如何改进
- 其他

谢谢!


#!/usr/bin/python

from __future__ import division
import os

# cant use: y == 0 and 0 or x / y
# because 0 eval to false, thus when y==0, it still performs x/y
def div (x,y):
if y==0: return 0
return x / y

operation = {'+' : lambda x,y : x + y,
'-' : lambda x,y : x - y,
'*' : lambda x,y : x * y,
'/' : lambda x,y : div(x,y)}

all_ops = operation.keys()

all_number_cand = (1,2,3,4,5,6,7,8,9,10)

def op_perm (ops=all_ops):
return [(i,j,k) for i in ops for j in ops for k in ops]

def number_perm (numbers=all_number_cand):
return [(i,j,k,l) for i in numbers for j in numbers for k in numbers for l in numbers]

### TODO increase the performace, it takes 10s
def main ():
result = []

for n_tuple in number_perm():
for o_tuple in op_perm():
o_stack = list(o_tuple)
n_stack = list(n_tuple)
n_queue = list(n_tuple)
while o_stack:
op = operation[o_stack.pop()]
n_stack.append(op(n_stack.pop(), n_stack.pop()))
n_queue.insert(0, op(n_queue.pop(), n_queue.pop()))
if 24 in n_stack or 24 in n_queue:
result.append((' ').join([str(n_tuple),str(o_tuple),str(n_stack),str(n_queue)]))

file = open('cal_res.txt','a')
for item in result:
file.writelines(item + os.linesep)
file.close()

if __name__=='__main__':
open('cal_res.txt','wb').write('') # any quick method?
main()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值