Start free

Beyond A level · 3 exercises

Python parsing

Turning text into structure: read it piece by piece (tokens: numbers, operators, brackets), then work out what they mean, in order.

A stack keeps what is waiting, such as an operator until both its numbers are known.

tokens = "3 4 + 2 *".split()
stack = []
for t in tokens:
    if t in "+*":
        b, a = stack.pop(), stack.pop()
        stack.append(a + b if t == "+" else a * b)
    else:
        stack.append(int(t))
print(stack[0])  # 14

Watch for: Never run the text with eval(): work it out yourself, so you decide what is allowed.

Exercises

  1. Expression calculatorEvaluate an expression with whole numbers, + - * and brackets, following the usualExpert
  2. Tidy a pathSimplify a Unix-style path: .Expert
  3. Number to Roman numeralsWrite a number from 1 to 3999 in Roman numerals, using the subtractive forms (IV,Expert
Start with “Expression calculator”