<p>Given a string <code>s</code> which represents an expression, <em>evaluate this expression and return its value</em>.&nbsp;</p>

<p>The integer division should truncate toward zero.</p>

<p>You may assume that the given expression is always valid. All intermediate results will be in the range of <code>[-2<sup>31</sup>, 2<sup>31</sup> - 1]</code>.</p>

<p><strong>Note:</strong> You are not allowed to use any built-in function which evaluates strings as mathematical expressions, such as <code>eval()</code>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>
<pre><strong>Input:</strong> s = "3+2*2"
<strong>Output:</strong> 7
</pre><p><strong class="example">Example 2:</strong></p>
<pre><strong>Input:</strong> s = " 3/2 "
<strong>Output:</strong> 1
</pre><p><strong class="example">Example 3:</strong></p>
<pre><strong>Input:</strong> s = " 3+5 / 2 "
<strong>Output:</strong> 5
</pre>
<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= s.length &lt;= 3 * 10<sup>5</sup></code></li>
	<li><code>s</code> consists of integers and operators <code>(&#39;+&#39;, &#39;-&#39;, &#39;*&#39;, &#39;/&#39;)</code> separated by some number of spaces.</li>
	<li><code>s</code> represents <strong>a valid expression</strong>.</li>
	<li>All the integers in the expression are non-negative integers in the range <code>[0, 2<sup>31</sup> - 1]</code>.</li>
	<li>The answer is <strong>guaranteed</strong> to fit in a <strong>32-bit integer</strong>.</li>
</ul>

def reduce_tokens_recursive(tokens):
    if len(tokens) == 1:
        return int(tokens[0])

    # 1. Find the first + or -
    for i, token in enumerate(tokens):
        if token == "+" or token == "-":
            left = reduce_tokens_recursive(tokens[:i])
            right = reduce_tokens_recursive(tokens[i+1:])
            if token == "+":
                return left + right
            else:
                return left - right

    # 2. Find the first * or /
    for i, token in enumerate(tokens):
        if token == "*" or token == "/":
            left = reduce_tokens_recursive(tokens[:i])
            right = reduce_tokens_recursive(tokens[i+1:])
            if token == "*":
                return left * right
            else:
                return left / right

def reduce_tokens_iterative(tokens):
    stack = []

    # Apply all * and / first and push onto stack
    # your issue was probably that you pushed them all first
    i = 0
    while i < len(tokens):
        if tokens[i] == "*" or tokens[i] == "/":
            left = stack.pop()
            right = tokens[i+1]
            if tokens[i] == "*":
                stack.append(left * right)
            else:
                stack.append(left // right)
            i += 2
        else:
            stack.append(tokens[i])
            i += 1

    # reverse the stack (so that we can go left --> right)
    stack.reverse()

    # Apply all + and - from the stack
    i = 0
    while len(stack) > 1:
        assert(len(stack) >= 3)
        left = stack.pop()
        op = stack.pop()
        right = stack.pop()
        if op == "+":
            stack.append(left + right)
        else:
            stack.append(left - right)

    return stack[0]

def tokenize(str):

    def is_operator(char):
        return char == "+" or char == "-" or char == "*" or char == "/"

    tokens = []
    i = 0
    while i < len(str):
        is_prev_token_operand = len(tokens) > 0 and is_operator(tokens[-1])

        if str[i] == " ":
            # space --> ignore it
            i += 1
        elif (not is_prev_token_operand) and (is_operator(str[i])):
            # operator --> add to tokens
            tokens.append(str[i])
            i += 1
        else:
            j = i
            while j < len(str) and (str[j].isdigit() or (j == i and str[j] == '-')):
                j += 1
            try:
                token = int(str[i:j])
            except Exception as e:
                raise Exception("Invalid expression provided: ", str[i:j])
            tokens.append(int(str[i:j]))

            i = j

    return tokens


class Solution:
    def calculate(self, str):
        # 1. Tokenize
        tokens = tokenize(str)

        # 2. Reduce the expression
        return reduce_tokens_iterative(tokens)


24400