The question is considered "not focused" because it asks to do too much. I assume that what you have in mind is something like: "recursively, process the tree according to the following rule: if the current node is a BinOp
and the children are both numeric constants, perform the operation and replace this node with the result".
There is nothing built-in that would do all of that. (There is, however, a NodeTransformer
class that can help with the graph-traversal aspect of the problem.) If you hadn't thought of an algorithm along those lines, then you either were hoping there would be such a built-in (in which case the answer is a simple "no") or you simply didn't take the appropriate steps to figure out the actual problem (i.e., where do you get stuck, trying to write the code for that algorithm?). If you had, then you should have said so, and shown your work so far.
However, even an algorithm like that wouldn't work for the example you showed. There is a well-known third-party library that does that kind of symbolic manipulation of expressions: it's called Sympy, and it's very heavyweight. I've never heard of simplified versions of that, because the application is too niche.
If you restrict yourself to + - / *
operators and integer constants, I believe it can be shown that the result will always be a polynomial in those constants (as would, necessarily, the result at each node). You theoretically could define a polynomial class that maps a tuple of (variable, exponent) tuples to the coefficient for the corresponding term of the polynomial, and use that to store intermediate results in the kind of traversal I described. If you restrict to a single variable with a given name, it could just be a list of coefficients for x^0, x^1 etc. Either way, you would want to use a rational number class to avoid floating-point inaccuracies (since integers are not closed under division). I hope you get the point, though: this would be way too much to ask for in a single question.
It is also good to do research before asking. I tried putting python ast simplify
into a search engine and readily found this previous question. site:docs.python.org ast
immediately finds the documentation, which allows for a quick scan for useful functionality. python symbolic computation
will tell you all about SymPy - admittedly, you have to have the concept in mind first.
ast
library, but I don't see why this would have been closed as Needs more focus. I could see Needs debugging details making sense since there doesn't appear to be an attempt at the desired output, or the current result of the code in the question.print
to be pasted into the question.