Model an equation as a tree
i want to model an开发者_开发百科 equation as a tree in python. for example:
x = exp(((-0.5)*((f/sqrt(d))**2)))
how do i do this? i want to be able to switch tree branches, delete parts of the tree etc, and then convert it back into a new equation in text form.
can you give me example code/ Libraries that can do this?
cheers edit 1:
I have come this far now:
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)
Now it prints all nodes of the tree. However i want to be able to switch branches, delete branches, insert branches and change operators/operands. I need this because i want to be able to mutate the tree randomly.
Operators and functions are parent nodes, and operands are the leaves.
x = exp(((-0.5)*((f/sqrt(d))**2)))
Start with a top-down approach: [ operator { operand1, operand2 }]
[ = { x, exp(((-0.5)*((f/sqrt(d))**2))) }]
followed by:
[ = { x, [ * { exp(((-0.5), ((f/sqrt(d))**2))) }] }]
then:
[ = { x, [ * { [ exp { -0.5 }], [ ** { f/sqrt(d)), 2 }] }] }]
You get the idea.
This link might be your answer.
PyParsing should be able to help you. (I'm assuming your equation might not necessarily be using the Python syntax itself, strictly speaking.)
What you want is to build and work with parse trees. Aside from the built-in parsing, if your equations go outside python's native syntax, take a look at this overview, which may be dated. Lots of options there.
精彩评论