Quantcast
Channel: Formula and math expression parser algorithm - Stack Overflow
Viewing all articles
Browse latest Browse all 3

Answer by Emmanuel for Formula and math expression parser algorithm

$
0
0

I don't know how to do this in C#, but python has a very powerful syntax tree analyzer (the ast module) that could help you here, if you give your expressions as python expressions (this is not so hard, you just have to add the '*' multiplication signs :-) ).

First, define the good class that only redefines the visit_Name method (called for identifiers, for instance another one visit_Expr is called for expressions, visit_Num is called when a number is met, etc, here we only want identifiers).

>>> import ast>>> class MyVisitor(ast.NodeVisitor):    def __init__(self, *args, **kwargs):        super(MyVisitor, self).__init__(*args, **kwargs)        self.identifiers = []    def generic_visit(self, node):        ast.NodeVisitor.generic_visit(self, node)    def visit_Name(self, node):        # You can specify othe exceptions here than cos or sin        if node.id not in ['cos', 'sin']:            self.identifiers.append(node.id)

Then define a quick function that takes an expression to give you its identifiers:

>>> def visit(expression):    node = ast.parse(expression)    v = MyVisitor()    v.visit(node)    print v.identifiers

It looks ok:

>>> visit('x + 4 * sin(t)')['x', 't']>>> visit('5*x + 7 ^ sin(z) / 2*T + 44')['x', 'z', 'T']

Use python 2.6 or 2.7 for the ast module.


Viewing all articles
Browse latest Browse all 3

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>