0

My problem is a bit complicated I would like to accept input equation from the user parse it and evaluate it. I want to have the ability to change a term or variable in that equation. I really do not know where to start. Should I make my own parser? or use something like lhs_parsed=pyparsing.parse(lhs).to_pyfunc() as I found in another post. I tried to execute that line but got pyparsing does not have attribute parse. I have using python 3.7.6 on windows

user3043108
  • 965
  • 1
  • 8
  • 10
  • There is a pyparsing-based project called `plusminus` that might be helpful for you. It comes with complete parser/evaluators for basic arithmetic, algebra, trig, business, and dice rolling. – PaulMcG Oct 12 '20 at 05:24

1 Answers1

0

You can use the ast module of python3 to parse the equation as shown in this answer(that one is in python2.6, but the ast module is in python3 as well). After you've recovered the Node type inside your equation you can use that to correctly evaluate your equation. This documentation can help you in the process. This is an example on how you can visit the tree:

import ast

class v(ast.NodeVisitor):
    def generic_visit(self, node):

        if type(node).__name__ == "Name":
            print(type(node).__name__, node.id)
        elif type(node).__name__ == "Constant":
            print(type(node).__name__, node.value)
        else:
            print(type(node).__name__)
        ast.NodeVisitor.generic_visit(self, node)

eq= 'sin(x)**2'
parsed= ast.parse(eq)
visitor = v()
visitor.generic_visit(parsed)

This code will print the identifier of a variable(x for example) or of a function(the sin funtion for example). You can also add these lines to evaluate an espression:

from math import sin
x = 2
print(eval(eq))

You can achieve a similar result by manipulating the nodes inside the Abstract Syntax Tree using a NodeTransformer as shown in this example.

trolloldem
  • 669
  • 4
  • 9
  • This works great but I have two questions: isn't using eval dangerous? and if I want to recompress the ast tree into string to be evaluated how can I do that – user3043108 Oct 29 '20 at 09:13
  • Also how can I define different versions of generic_visit. I want to use it to change the expression and that worked for me but I need to do different changes at different times – user3043108 Oct 29 '20 at 09:16
  • I tried using eval(copiled(tree,filename="", mode="exec") but it did not work. It resulted in an object in the variable explorer – user3043108 Oct 29 '20 at 10:11