Problem 290364 · medium · Phase 02 Linear Data Structures

Tokenise an Arithmetic Expression

strings · parsing · tokenising

Write tokenise(expr) that splits an arithmetic expression into a list of tokens. A token is either a non-negative integer (a maximal run of digits), one of the operators + - * /, or a parenthesis ( ). Whitespace separates tokens but is never a token itself.

Examples

Input:  expr = "12+ 3*(45-6)"
Output: ["12", "+", "3", "*", "(", "45", "-", "6", ")"]

Input:  expr = "  7  "
Output: ["7"]

Input:  expr = ""
Output: []

Constraints

  • 0 <= len(expr) <= 10**5, containing only digits, +-*/() and spaces
  • A - is always an operator token, never a sign
  • Target: O(n) time

Goals

  • Group consecutive digits into one token
  • Emit single-character tokens for operators and brackets
  • Skip whitespace without producing tokens
Starting Python…