3/38
Part 1 of 7 · TreesLearn

The input comes as pairs, so build one dict for each direction

Here is the tree the way input gives it: one row for each region.

# (region, the region directly containing it)
PAIRS = [
    ("Portugal", "Europe"), ("Spain", "Europe"),
    ("Lisbon District", "Portugal"), ("Porto District", "Portugal"),
    ("Lisbon", "Lisbon District"), ("Sintra", "Lisbon District"), ("Cascais", "Lisbon District"),
    ("Porto", "Porto District"),
    ("Andalusia", "Spain"), ("Catalonia", "Spain"),
    ("Seville", "Andalusia"), ("Granada", "Andalusia"),
]
print(len(PAIRS), "pairs")
12 pairs

The input rarely arrives drawn as a tree. It comes as rows, and each row names a region and its parent. Two dicts hold everything you'll need, one for each direction:

from collections import defaultdict


def build_tree(pairs):
    # region -> the regions directly inside it
    children = defaultdict(list)
    # region -> the region directly containing it
    parent = {}
    for region, outer in pairs:
        children[outer].append(region)
        parent[region] = outer
    tops = {outer for _, outer in pairs} - set(parent)
    return children, parent, tops


children, parent, tops = build_tree(PAIRS)
print(children["Lisbon District"])
print(parent["Sintra"])
print(tops)
print(len(children))
Predict

children is a defaultdict(list), filled from the 12 pairs. What does len(children) print?

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