The supply officer asks two more things. How many crew share the supplies? And can we add a new supply when a cargo ship arrives?
Rocket grins. "Counting the crew is a tree job. I know that one!"
Raven asks, "What do you notice about adding a supply we have never had before?"
"Its key is not in the dictionary yet," Rocket says. "So I cannot add to it."
Nova hums. "Here is a hint. Check if the key is there first."
# Part 5: crew and restock
def count_crew(node):
total = 1
for child in node["crew"]:
total = total + count_crew(____)
return total
def restock(stock, item, amount):
if item in stock:
stock[item] = stock[item] + amount
else:
stock[item] = ____
def count_crew(node):
total = 1
for child in node["crew"]:
total = total + count_crew(child)
return total
def restock(stock, item, amount):
if item in stock:
stock[item] = stock[item] + amount
else:
stock[item] = amount
team = {"name": "Bo", "crew": [{"name": "Cy", "crew": []}]}
print(count_crew(team))
stock = {"rope": 2}
restock(stock, "rope", 10)
restock(stock, "kites", 4)
print(stock) Output:
2
{'rope': 12, 'kites': 4} | Statement | True or false? |
|---|---|
| restock changes the dictionary it is given. | ? |
| restock crashes for a supply that is not in the dictionary yet. | ? |
| count_crew uses recursion. | ? |
def count_crew(node):
total = 1
for child in node["crew"]:
total = total + count_crew(child)
return total
def restock(stock, item, amount):
if item in stock:
stock[item] = stock[item] + amount
else:
stock[item] = amount
team = {"name": "Eve", "crew": [
{"name": "Fen", "crew": []},
{"name": "Gil", "crew": []},
{"name": "Hal", "crew": []},
]}
print(count_crew(team))
stock = {"maps": 7}
restock(stock, "maps", 3)
restock(stock, "glue", 6)
restock(stock, "glue", 1)
print(stock) | Statement | True or false? |
|---|---|
| count_crew(team) visits four nodes. | ? |
| restock(stock, "glue", 6) crashes because glue is new. | ? |
| restock changes the stock dictionary. | ? |
| in checks whether a key is in a dictionary. | ? |
Part 5 done! Every helper is built and test driven. Tomorrow we add the tests and the report, and run the whole thing.