16/38
Part 4 of 7 · PathsLearn and do

Paths and the smallest common ancestor

With a parent dict, a question about a path is a climb.

def path_from_top(parent, region):
    path = [region]
    # the top has no parent, so the loop ends there
    while region in parent:
        region = parent[region]
        path.append(region)
    return path[::-1]


print(path_from_top(parent, "Sintra"))
['Europe', 'Portugal', 'Lisbon District', 'Sintra']

Going up needs no search at all. The walk is O(d)O(d), where dd is the region's depth. It's a loop, so a deep chain is no problem.

In the editor, write depth_of(parent, region) by climbing. It prints the depth of the top, of Sintra, and of the end of a chain of 50,000.