New crew need a printed chart of the command tree. Rocket prints all the names in one long column.
"Hmm. It is all there, but you cannot tell who leads who," Rocket says.
Raven tilts the chart sideways. "What do you notice about how deep each person is in the tree?"
"Ada is at depth 0. Bo and Eve are 1 step down. Their crew are 2 steps down," Rocket says.
Nova hums. "Here is a hint. Push each name to the right by its depth."
The show function takes a node and a depth. It prints two spaces for each level of depth, then the name. Each child is shown one level deeper.
fleet = {
"name": "Ada",
"crew": [
{"name": "Bo", "crew": [
{"name": "Cy", "crew": []},
{"name": "Dee", "crew": []},
]},
{"name": "Eve", "crew": [
{"name": "Fen", "crew": []},
{"name": "Gil", "crew": []},
{"name": "Hal", "crew": []},
]},
],
}
def show(node, depth):
print(" " * depth + node["name"])
for child in node["crew"]:
show(child, depth + 1)
show(fleet, 0) Output:
Ada
Bo
Cy
Dee
Eve
Fen
Gil
Hal Notice the order. show finishes all of Bo's tree before it starts Eve. Each call goes as deep as it can before moving on.
ship = {
"name": "Ship",
"parts": [
{"name": "Deck A", "parts": [
{"name": "Lab", "parts": []},
{"name": "Dock", "parts": []},
]},
{"name": "Deck B", "parts": [
{"name": "Bridge", "parts": []},
{"name": "Hold", "parts": []},
]},
],
}
def show(node, depth):
print(" " * depth + node["name"])
for part in node["parts"]:
show(part, depth + 1)
show(ship, 0) | Statement | True or false? |
|---|---|
| Ship prints with no spaces. | ? |
| Bridge prints before Dock. | ? |
| Each child is shown one level deeper. | ? |
| show prints every node once. | ? |
Great job! You printed a tree the way computers show folders inside folders. Tomorrow we search the tree.