7/38
Part 2 of 7 · RecursionLearn and do

Pre-order works before the children, post-order after them

Where the work sits next to the calls on the children decides what each region knows.

def walk(region, depth, pre, post):
    # pre-order: before the children
    pre.append((region, depth))
    for child in children[region]:
        walk(child, depth + 1, pre, post)
    # post-order: after them
    post.append(region)


pre, post = [], []
walk("Europe", 0, pre, post)
print(f"{'pre, with depth':<24}post")
for (region, depth), finished in zip(pre, post):
    print(f"{region + ' ' + str(depth):<24}{finished}")
Predict

post records a region after all its children. Which region comes first in post-order?

Pick one to see what it prints.
Pick an answer above to see the rest