Mission Control asks how many crew are in the fleet. Rocket starts writing loops inside loops.
"One loop for the leads, one loop for their crew," he says. "But what if a pilot gets their own crew someday?"
Raven points at Bo's part of the tree. "What do you notice about counting Bo's team?"
"It is the same job as counting the whole fleet!" Rocket says. "Just a smaller tree."
Nova glows. "Here is a hint. Count yourself, then ask each child to count their own tree."
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 count(node):
total = 1
for child in node["crew"]:
total = total + count(child)
return total
print(count(fleet)) Output: 8
| Call | Returns |
|---|---|
| count(Cy) | 1 |
| count(Dee) | 1 |
| count(Bo) | 1 + 1 + 1 = 3 |
| count(Fen), count(Gil), count(Hal) | 1 each |
| count(Eve) | ? |
| count(Ada) | 1 + 3 + count(Eve) = 8 |
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 count(node):
total = 1
for part in node["parts"]:
total = total + count(part)
return total
print(count(ship))
print(count(ship["parts"][0]))
print(count(ship["parts"][0]["parts"][0])) | Statement | True or false? |
|---|---|
| count(ship["parts"][1]) returns 3. | ? |
| count needs a separate if line for leaves. | ? |
| The empty parts list works like a base case. | ? |
| count works on the fleet if parts is changed to crew. | ? |
Brilliant! One short function counts any tree, no matter how deep. Tomorrow we print the tree with indents.