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
inttoken ("120"is120). - Each of
+ - * / ( )is a one-characterstrtoken. 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().