18/38
Part 4 of 7 · PathsLearn
Without parent links, keep the path in a list and take off what led nowhere
When a tree arrives as nested objects that only point down, there's no parent to climb. Find the path with a walk down that keeps the current path in a list. Append on the way in, and pop on the way out when the target wasn't below:
def path_down(children, top, target):
path = []
def visit(region):
path.append(region)
if region == target:
return True
for child in children[region]:
if visit(child):
return True
# not under here: take it back off
path.pop()
return False
visit(top)
return path
print(path_down(children, "Europe", "Granada"))
['Europe', 'Spain', 'Andalusia', 'Granada']
The list grows on the way down and shrinks on the way back up:
| Visit | path after it |
|---|---|
| Europe | Europe |
| Portugal | Europe, Portugal |
| Portugal's subtree | its 7 regions go on, then come back off |
| back out of Portugal | Europe |
| Spain | Europe, Spain |
| Andalusia | Europe, Spain, Andalusia |
| Seville | Europe, Spain, Andalusia, Seville: not the target, so popped |
| Granada | Europe, Spain, Andalusia, Granada: the target, stop |
This walk may visit the whole tree, , against for the walk up. So build parent once if you'll ask more than one question. That path.pop() is your first undo step. Backtracking, later in this lesson, is built on it.