runtime

compare approaches one problem · two ways

Compare Approaches

The same problem solved different ways in Python, run on the same input, with what really differs and when to use each.

Recursion vs iteration

Total the sizes in a nested folder structure.

what differs

The recursive version uses Python's call stack; the iterative one keeps its own list. Python stops recursion around 1,000 levels deep (RecursionError).

at a glance

approachuse it when
A · recursiveTree-shaped data of modest depth: the code mirrors the structure.
B · explicit stackDeep or untrusted structures (no recursion limit) or hot loops.

Watch out: The stack visits nodes in a different order (last in, first out); use a deque and popleft() for breadth-first order.

the outputs

Each approach runs on the same input.

concepts

recursionstackRecursionError

learn it

Inline functions with lambda

related comparisons

Memoising: dict vs lru_cache vs cache · Iterator class vs generator function

A · recursive
B · explicit stack
Compare Python Approaches · Runtime