Calculate the equation given a string
<p>Given a random equation (with plus and multiply), calculate the result. </p>

<p>For example, given, "5 + 3 * 4 * 2 + 1", return 30.</p>

<p>This was a question I was given on a programming interview (a year ago) and was told to do it in at least 0(n) time. </p>

<p>I attempted to do it in python. </p>

<p>Built-in function <code>eval()</code> <strong><em>not recommended</em></strong> as a go-to, but is rather quite helpful in this particular case:</p>

<pre><code>string = "5 + 3 * 4 * 2 + 1"
print (eval(string))
# 30
</code></pre>

<p>Though there are quite an amount of side-effects and risks using <code>eval()</code>. So don't use quite often.<br>
one quite useful way would be to extract the operators and the operands seperately and then do the desired arithmetic.</p>

<pre><code>operands = [int(x) for x in string if x.isdigit()] # not using re as this is faster
# [5, 3, 4, 2, 1]

operators = re.findall(r"[^\d\s]", string)
# ['+', '*', '*', '+']
</code></pre>

<p>Now you can apply the operators to the two corresponding operands in a function maybe. <em>Just make sure to keep proper <strong>arithmetic convention</strong></em> (<code>*</code> should come before <code>+</code>)</p>

python math equation