【Python】二叉树解24点

利用二叉树遍历解决24点问题

Source Code

#!/usr/bin/python
# -*- coding: utf-8 -*-
# @Time   : 2020/11/12 21:50
# @Author : SandQuant


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 generate_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 solve_24(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]

    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]:
        root, leaf, root_leaf = generate_tree(tree)
        solve_24(root, leaf, root_leaf, operation, num)

Output

pro(sub(4,div(4,7)),7)
pro(7,sub(4,div(4,7)))

分别代表:
pro(sub(4,div(4,7)),7):(4-(4/7))7=24
pro(7,sub(4,div(4,7))):7
(4-(4/7))=24
本质是一样的,但运算顺序不同



欢迎关注~ SandQuant 专注于全球金融数据和量化投资策略

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
二叉树期权定价是一种常用的数值方法,可以用来估计期权的价格。在Python中,可以使用二叉树模型来实现期权定价。下面是一个示例的Python代码: ```python import numpy as np def tree_option(S, X, r, sigma, t, steps): u = np.exp(sigma * np.sqrt(t / steps)) d = 1 / u P = (np.exp(r * t / steps) - d) / (u - d) prices = np.zeros(steps + 1) c_values = np.zeros(steps + 1) prices\[0\] = S * d ** steps c_values\[0\] = np.maximum(prices\[0\] - X, 0) for i in range(1, steps + 1): prices\[i\] = prices\[i - 1\] * (u ** 2) c_values\[i\] = np.maximum(prices\[i\] - X, 0) for j in range(steps, 0, -1): for i in range(0, j): c_values\[i\] = (P * c_values\[i + 1\] + (1 - P) * c_values\[i\]) / np.exp(r * t / steps) return c_values\[0\] ``` 这段代码使用了欧式期权的二叉树定价方法,其中S是标的资产价格,X是行权价格,r是无风险利率,sigma是标的资产的波动率,t是期权的剩余时间,steps是二叉树的步数。函数返回的是期权的价格。 请注意,这只是一个简单的示例代码,实际应用中可能需要根据具体的需求进行修改和扩展。引用\[1\]提供了一个完整的二叉树期权定价的Python代码,你可以参考该代码进行更详细的了和实践。 #### 引用[.reference_title] - *1* [(三十九)期权定价的二叉树法](https://blog.csdn.net/hzk427/article/details/104614876)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* [pythonzuobiaoxi方程_【定价】二叉树(CRR)欧式/美式期权定价的原理及Python实现...](https://blog.csdn.net/weixin_39785814/article/details/109918446)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] - *3* [期权定价的数值方法之二项式期权定价模型【附pyrhon代码】](https://blog.csdn.net/xiaowu1997/article/details/121730380)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值