<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>

from typing import List, Union




class Solution:
    def calculate(self, s: str) -> int:
        tokens: List[Union[int, str]] = tokenize(s)
        stack = [
            State(0, "+", None)
        ]
        for token in tokens:
            top_state = stack[-1]
            if token in ("*", "/"):
                if top_state.operator is None:
                    top_state.operator = token
                else:
                    operand_2 = top_state.operand_2
                    top_state.operand_2 = None
                    new_state = State(operand_2, token, None)
                    stack.append(new_state)
            elif token in ("+", "-"):
                if top_state.is_complete():
                    top_state.calculate()
                top_state.operator = token
            else: # A number
                top_state.set_operand(token)
                if top_state.is_complete():
                    # Handle computation 
                    if top_state.operator in ("*", "/"):
                        top_state.calculate()
                        ans = top_state.operand_1
                        stack.pop()
                        new_top_state = stack[-1]
                        new_top_state.set_operand(ans)
                    elif top_state.operator in ("+", "-"):
                        pass
                    else:
                        raise Exception("Invalid")
        if stack[0].is_complete():
            stack[0].calculate()
        return stack[0].operand_1

class State: 
    def __init__(self, operand_1, operator, operand_2):
        self.operand_1 = operand_1
        self.operator = operator
        self.operand_2 = operand_2

    def __repr__(self) -> str:
        return f"<{self.operand_1}{self.operator}{self.operand_2}>"

    def set_operator(self, new_operator):
        if self.operator is None:
            self.operator = operator
        else:
            raise Exception("Invalid state")
    
    def set_operand(self, new_operand):
        if self.operand_1 is None and self.operand_2 is None:
            self.operand_1 = new_operand
        elif self.operand_1 is not None and self.operand_2 is None:
            self.operand_2 = new_operand
        else:
            raise Exception("Invalid state")
    
    def is_empty() -> bool:
        return self.operand_1 is None and self.operator is None and self.operand_2 is None

    def is_complete(self) -> bool:
        if self.operand_1 is None:
            return False
        if self.operator is None:
            return False
        if self.operand_2 is None:
            return False
        return True
 
    def clear(self):
        self.operand_1 = None
        self.operator = None
        self.operand_2 = None

    def calculate(self):
        if self.operator == "*":
            ans = self.operand_1 * self.operand_2
        elif self.operator == "/":
            ans = self.operand_1 // self.operand_2
        elif self.operator == "+":
            ans = self.operand_1 + self.operand_2
        elif self.operator == "-":
            ans = self.operand_1 - self.operand_2
        else:
            raise Exception("Invalid operator")
        self.clear()
        self.operand_1 = ans

def tokenize(s: str) -> List[Union[int, str]]:

    tokens: List[Union[int, str]] = []

    has_number = False
    number = 0

    def add_number_if_exists():
        nonlocal has_number, number
        if has_number:
            tokens.append(number)
            has_number = False
            number = 0
    
    non_space_chars: List[str] = [c for c in s if c != ' ']
    for char in non_space_chars:
        if char.isdigit():
            has_number = True
            number *= 10
            number += int(char)
        else:
            add_number_if_exists()
            tokens.append(char)
    
    add_number_if_exists()
    return tokens
23700