-1

I am trying to write a simple method to parse a string equation like "5*3-3+13" and calculate the result without using eval(). I have a problem with how to set the operator precedence. My initial idea is to use recursion, but I have trouble when there is continuous multiplication or division in the equation. Another idea is to just loop through the equation to find the multiplication and division first, but that takes too much time. Is there an idea that I can utilize?

Wilbert
  • 149
  • 7
  • Is there any reason behind doing that? I mean, `sympy` a great python package that can do just exactly that and more. – Anwarvic May 17 '20 at 09:23
  • `eval` would be the *quick* solution, but using a for loop approach with operator checking would be better, or using a python `parser` coupled with `eval` – de_classified May 17 '20 at 09:23
  • I just want to learn how it works – Wilbert May 17 '20 at 09:27
  • Actually, I have just found the algorithm needed called "Shunting-yard and Postfix Calculator Algorithms", thanks – Wilbert May 17 '20 at 10:10

1 Answers1

1

What you are trying to do is parsing and evaluating a simple algebraic expression. This is a well covered topic, and you don't necessarily need to use python eval, especially if you are worried with code injection.

You can quickly solve that using existing libraries. My first thought would be sympy.

E.g.

import sympy
f = sympy.sympify("5*3-3+13")

The value you expect is either int(f) or double(f) depending on whether you want integers or want to allow floats

Chris
  • 387
  • 1
  • 8