Structured token ladders

Beginner Defensive APIs: validation, sanitization & exceptions
Created by Pavel · 29.04.2026 at 19:10 UTC

Unary-free arithmetic ladders alternate operand, operator, operand, … with odd length: [10, '+', 2, '*', 3] has five tokens. Checking parity and digit/operator roles before casting to floats prevents ValueError explosions halfway through evaluation—better error messages, less partial state.

CSV and JSON pipelines use the same discipline: verify column count and dtype expectations before vectorised math.

Formal grammars generalise ladders; for small teaching kernels, explicit index parity is enough.

str.isdigit reference: [1].


Sources

University approvals: 0
Tasks
Question 1

For a unary-free infix ladder starting and ending with operands, the number of tokens is always:

Hint

Operand/operator alternation with operands on both ends.

Question 2

Why validate token structure before float(tok) on operands?

Hint

Catch shape errors before coercion.

Question 3

valid_ladder(parts, ops) is True iff len(parts) >= 3, odd length, even indices are digit-only strings, odd indices are in set ops.

Hint

Index parity encodes operand vs operator slots.

Starter code is prefilled; replace TODO blocks with your solution.
2 test cases will be used for grading
Run checks runtime behavior only. Final correctness is evaluated when you submit.
Card Info
  • Topic: Defensive APIs: validation, sanitization & exceptions
  • Difficulty: Beginner
  • Completed: 0 users
Creator
Pavel
Pavel