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>Assuming you didn't want to use eval, you can try and do this inline. </p>

<p>A good problem solving technique for this kind of question is to write out what you would want to happen. </p>

<p>If you are looking at this item by item, you will notice that when we have addition, you can safely add all the previous results together. With multiplication we always have to wait for the next item. </p>

<pre><code>def strToCal(strings):
    first = 0;
    second = 0;

    list1 = []
    list1 = strings.split()

    mult = False

    for i in list1:

        if i == "+":
            first += second
            second = 0
            mult = False
        elif i == "*":
            mult = True
        else:
            if mult:
                second *= int(i)
            else:
                second = int(i)

    return (first + second)


print strToCal("5 * 34 * 75 * 2 + 1")
</code></pre>

python math equation