Parse and Evaluate Simple Arithmetic Tokens
StringsAuto-graded · 17 test casesLast updated
Tests the ability to tokenize a raw arithmetic string into numbers and operators, then evaluate left-to-right respecting only + and - operations.
Parse and Evaluate Simple Arithmetic Tokens
You are given a string representing a simple arithmetic expression containing non-negative integers, and the operators + and -. Your task is to tokenize the string and evaluate it.
The expression is evaluated strictly left-to-right (no operator precedence — there is no * or /). Tokens are separated by zero or more spaces.
Write a function that takes such a string and returns the integer result of evaluating it.
Rules
- The expression always starts with a non-negative integer.
- Operators are always binary (no unary minus).
- Numbers are non-negative integers (may be multi-digit).
- There are no parentheses.
- There may be multiple spaces (including none) between tokens.
- Leading and trailing spaces are possible.
- A string containing only a single number (no operators) is valid.
Constraints
1 <= len(expression) <= 2000- All numbers in the expression are in the range
[0, 10^9]. - The expression always contains at least one number.
- The expression is always valid (no malformed tokens, no division, no multiplication).
- The result may be negative (e.g.,
"3 - 10"). - The result fits in a standard Python
int.
Examples
Example 1
Input: evaluate_expression('10 + 3 - 2')
Output: 11
Example 2
Input: evaluate_expression(' 42 ')
Output: 42
Example 3
Input: evaluate_expression('100 - 200 + 50')
Output: -50
Hints
Hint 1
Split the problem into two phases: first collect all tokens (numbers and operators) from the string, then walk through them to compute the result.
Hint 2
You can iterate character by character, accumulating digit characters into a current number buffer and emitting a token whenever you hit a non-digit (non-space) character or the end of the string.
Hint 3
Once you have a flat list of tokens, process them with a simple index walk: keep a running total and a pending operator (+/-), applying each operator as you encounter the next number.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The solution has two clean phases that mirror what "tokenizing" means in practice.
Phase 1 — Tokenize
Walk the string character by character:
- Skip spaces.
- When an operator (
+or-) is found, emit it as a string token. - When a digit is found, consume all consecutive digits and emit the resulting
inttoken.
This produces a flat list like [10, '+', 3, '-', 2].
Phase 2 — Evaluate
The token list always has the shape [num, op, num, op, num, ...]. Start with result = tokens[0], then step through pairs (operator, number) in groups of two, applying each operation to the running total.
Why it is correct
- Every character is classified as space, operator, or digit — no case is missed.
- Left-to-right evaluation is enforced by processing operator-number pairs in order without any lookahead or stack.
- Multi-digit numbers are handled by the inner
while j < n and expression[j].isdigit()loop. - Edge cases (single number, all zeros, large numbers, extra spaces) all fall through the same code path naturally.
Complexity
| Time | O(L) where L = len(expression) — one pass to tokenize, one pass to evaluate |
| Space | O(T) where T = number of tokens ≤ L |
Reference Solution
def evaluate_expression(expression: str) -> int:
# --- Tokenize ---
tokens = []
i = 0
n = len(expression)
while i < n:
ch = expression[i]
if ch == ' ':
i += 1
elif ch in '+-':
tokens.append(ch)
i += 1
else: # digit
j = i
while j < n and expression[j].isdigit():
j += 1
tokens.append(int(expression[i:j]))
i = j
# --- Evaluate left-to-right ---
result = tokens[0] # first token is always a number
idx = 1
while idx < len(tokens):
op = tokens[idx] # '+' or '-'
num = tokens[idx + 1] # the following number
if op == '+':
result += num
else:
result -= num
idx += 2
return result