将方程建模为树

0 投票
3 回答
1800 浏览
提问于 2025-04-16 19:41

我想在Python中把一个方程建模成一棵树。
比如:

x = exp(((-0.5)*((f/sqrt(d))**2)))

我该怎么做呢?我希望能够切换树的分支,删除树的一部分等等,然后再把它转换回新的文本形式的方程。

你能给我一些示例代码或者可以实现这个功能的库吗?

谢谢!
编辑 1:

我现在已经做到这一步了:

import compiler
import pprint
import parser
import ast
class Py2Neko(ast.NodeTransformer):
    def generic_visit(self, node):
        print type(node).__name__
        ast.NodeVisitor.generic_visit(self, node)

    def visit_Name(self, node):
        print 'Name :', node.id

    def visit_Num(self, node):
        print 'Num :', node.__dict__['n']

    def visit_Str(self, node):
        print "Str :", node.s

    def visit_Print(self, node):
        print "Print :"
        ast.NodeVisitor.generic_visit(self, node)

    def visit_Assign(self, node):
        print "Assign :"
        ast.NodeVisitor.generic_visit(self, node)

    def visit_Expr(self, node):
        print "Expr :"
        ast.NodeVisitor.generic_visit(self, node)

if __name__ == '__main__':
    node = ast.parse("res= exp(((-0.5*one)*((delta_w*one/delta*one)**2)))")

    # print ast.dump(node)
    v = Py2Neko()
    v.visit(node)

现在它可以打印出树的所有节点。不过我希望能够切换分支,删除分支,插入分支,以及更改运算符和操作数。
我需要这样做是因为我想随机改变这棵树。

3 个回答

0

你想要做的是构建和使用解析树。除了Python自带的解析功能,如果你的方程式超出了Python的基本语法,可以看看这个概述,虽然可能有点过时,但里面有很多选择。

0

PyParsing 这个工具应该能帮到你。(我假设你的方程式可能并不一定严格使用Python的语法。)

1

运算符和函数是父节点,而操作数是叶子节点。

x = exp(((-0.5)*((f/sqrt(d))**2)))

从上到下的方式开始:[ 运算符 { 操作数1, 操作数2 }]

[ = { x, exp(((-0.5)*((f/sqrt(d))**2))) }]

接下来是:

[ = { x, [ * { exp(((-0.5), ((f/sqrt(d))**2))) }] }]

然后:

[ = { x, [ * { [ exp { -0.5 }],  [ ** { f/sqrt(d)), 2 }] }] }]

你明白这个意思了吧。

这个 链接 可能会给你答案。

撰写回答