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
| approach | use it when |
|---|---|
| A · recursive | Tree-shaped data of modest depth: the code mirrors the structure. |
| B · explicit stack | Deep 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
related comparisons
Memoising: dict vs lru_cache vs cache · Iterator class vs generator function