11/38
Part 3 of 7 · Your own stackLearn and do

Raising the limit too far can crash Python, so keep the pending work in a list

sys.setrecursionlimit raises the limit. Python's docs warn that it should be done with care, because a limit set too high can crash Python.

Interview inputs come from someone else. A tree of a million nested comments, or a folder chain from a broken script, is fair game. The safe answer is to keep the pending work in a list you manage, instead of on Python's call stack.

A Python list is a stack already. append puts an item on the end, and pop() with no index takes the last one back off. Push the top, then pop a region, handle it, and push its children, until the stack is empty:

# pre-order work: known before the children
def depths_with_stack(children, top):
    depth = {top: 0}
    stack = [top]
    while stack:
        region = stack.pop()
        for child in children[region]:
            depth[child] = depth[region] + 1
            stack.append(child)
    return depth


depth = depths_with_stack(children, "Europe")
print(depth["Portugal"], depth["Sintra"], depth["Catalonia"])
1 3 2

Pre-order work fits straight in, because a child's depth is known the moment its parent is popped. Here is the stack after each pop on Portugal's subtree, with its top at the right end:

stack = ["Portugal"]
while stack:
    region = stack.pop()
    stack.extend(children[region])
    print(f"{region:<17}{stack}")
Predict

The stack starts as ["Portugal"]. Each pop puts the region's children on the end. Which region comes off second?

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