progress

~/problems / Iterators & parsers / Parsers and interpreters

Tokenize an arithmetic expression

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy basics ~10 min

Every parser starts with a tokenizer: it turns raw text into meaningful pieces so the parser never thinks about spaces or single digits.

Implement tokenize(s: str) -> list:

  • A run of digits is one int token ("120" is 120).
  • Each of + - * / ( ) is a one-character str token. A - is always "-", even before a number: unary minus is the parser's job.
  • Whitespace separates tokens and is skipped, so "1 2" is [1, 2].
  • Any other character raises ValueError (ideally naming it and its index).
tokenize("12 + 3*(40-5)")
# [12, "+", 3, "*", "(", 40, "-", 5, ")"]

tokenize("  7 ")    # [7]
tokenize("-8")      # ["-", 8]
tokenize("")        # []
tokenize("2 ^ 3")   # ValueError: unexpected character '^' at index 2
Show hint

walk an index i; at a digit, advance a second index while it's still a digit and convert the slice with int().

Topic: Parsers and interpreters. Tokenize, recursive descent, S-expressions, evaluation and type inference.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc