from dataclasses import dataclass from typing import Union class LexError(Exception): pass @dataclass class Token: kind: str value: Union[int, float, str, None] def tokenize(src: str) -> list: tokens = [] i = 0 while i < len(src): ch = src[i] if ch in ' \t': i += 1 continue if ch.isdigit() or ch == '.': j = i has_dot = False while j < len(src) and (src[j].isdigit() or (src[j] == '.' and not has_dot)): if src[j] == '.': has_dot = True j += 1 raw = src[i:j] value = float(raw) if has_dot else int(raw) tokens.append(Token('NUMBER', value)) i = j continue if ch == '+': tokens.append(Token('PLUS', '+')) elif ch == '-': tokens.append(Token('MINUS', '-')) elif ch == '*': tokens.append(Token('STAR', '*')) elif ch == '/': tokens.append(Token('SLASH', '/')) elif ch == '(': tokens.append(Token('LPAREN', '(')) elif ch == ')': tokens.append(Token('RPAREN', ')')) else: raise LexError(f"unexpected character {ch!r} at position {i}") i += 1 tokens.append(Token('EOF', None)) return tokens