python24点问题_python:基于二叉树速解凑24点问题

# 暨南大学 王杰安

import itertools

def add(a, b):

return a+b

def sub(a, b):

return a-b

def pro(a, b):

return a*b

def div(a, b):

return a/b

def wcd_find_tree(tree):

root = []; root_leaf = [] deep = max(map(lambda x: x[0], tree))

trees = dict.fromkeys(range(1,deep+1), [])

for leaf in tree:

trees[leaf[0]] = trees[leaf[0]]+[leaf] for level in range(1,deep+1):

for i in range(int(len(trees[deep+1-level])/2)):

_1 = trees[deep+1-level][i*2] _2 = trees[deep+1-level][i*2+1] father_root= (_1[0]-1, int((_1[1]+_2[1]+1)/4))

if father_root in trees[deep-level]:

root.append(str(father_root))

root_leaf.append([str(father_root), '{}({},{})'.format(father_root,_1,_2)])

root_leaf.sort()

for i in range(1,len(root_leaf)):

target = root_leaf[0][1] tool_key = root_leaf[i][0] tool = root_leaf[i][1] root_leaf[0][1] = target.replace(tool_key,tool)

leaf = [str(x) for x in tree if str(x) not in root] root.sort(); leaf.sort()

return root, leaf, root_leaf[0][1]

def wja_solve(root, leaf, function, operation, num):

num_combine = list(set(list(itertools.permutations(num, 4))))

ope_combine = list(itertools.product(operation, repeat=3))

for nums in num_combine:

for opes in ope_combine:

equation = function

foot_function = dict(zip(root, list(opes)))

leaf_function = dict(zip(leaf, list(nums)))

replace_rule = dict(foot_function, **leaf_function)

for key in replace_rule.keys():

equation = equation.replace(key, str(replace_rule[key]))

try:

if eval(equation)==24:

print(equation)

except:

continue

if __name__ == '__main__':

operation = ['add', 'sub', 'pro', 'div']; num = [4,4,7,7] # 树构造,这一块懒得写代码了,这一块由于24点的特殊性,所以跳过树构造的过程

# 理论上这里还可以写一个树构造的代码,有兴趣的自己写一写

tree_1 = [(1,1),(2,1),(2,2),(3,1),(3,2),(3,3),(3,4)] tree_2 = [(1,1),(2,1),(2,2),(3,1),(3,2),(4,1),(4,2)] tree_3 = [(1,1),(2,1),(2,2),(3,1),(3,2),(4,3),(4,4)] tree_4 = [(1,1),(2,1),(2,2),(3,3),(3,4),(4,5),(4,6)] tree_5 = [(1,1),(2,1),(2,2),(3,3),(3,4),(4,7),(4,8)] for tree in [tree_1, tree_2, tree_3, tree_4, tree_5]:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值