followup code

Hi Roger, it happens there is a more native way to evaluate string expression in python eval(). Catch is that for safety reasons, using eval() on raw user input is not good practice. So added an input check to raise an exception.
 avataruser_9809957
python
2 months ago
1.8 kB
4
Indexable
Never
def is_safe_expression(expr: str) -> bool:
    allowed_chars = set('0123456789+-() ')
    for char in expr:
        if char not in allowed_chars:
            return False
    return True

def evaluate_expression(expr: str) -> int:
    if not is_safe_expression(expr):
        raise ValueError("Unsafe expression!")
    
    return int(eval(expr))

# Test cases
print(evaluate_expression('1+20'))  # 21
print(evaluate_expression('10-2+40'))  # 48
print(evaluate_expression('10- (1- 9)'))  # 18

# complete python
def evaluate_exp(expr: str) -> int:
    def operate(a, b, op):
        if op == '+':
            return a + b
        elif op == '-':
            return a - b
        return 0

    def compute():
        op = operators.pop()
        b = values.pop()
        a = values.pop()
        values.append(operate(a, b, op))

    values, operators = [], []
    i = 0
    while i < len(expr):
        if expr[i] == ' ':
            i += 1
            continue
        if expr[i] in '0123456789':
            j = i
            while j < len(expr) and expr[j].isdigit():
                j += 1
            values.append(int(expr[i:j]))
            i = j
        elif expr[i] in "+-":
            while operators and operators[-1] in "+-":
                compute()
            operators.append(expr[i])
            i += 1
        elif expr[i] == '(':
            operators.append(expr[i])
            i += 1
        elif expr[i] == ')':
            while operators[-1] != '(':
                compute()
            operators.pop()  # pop the '('
            i += 1
    while operators:
        compute()
    return values[0]

# Test
print(evaluate_exp('1+20'))  # 21
print(evaluate_exp('10-2+40'))  # 48
print(evaluate_exp('10-(1-9)'))  # 18

# same logic written in cpp
https://pastecode.io/s/aakvx8rc