Rocket opens a blank file for the inventory tracker. He stares at it. "Where do I even start?"
Raven draws a box labeled Tracker. Under it she draws smaller boxes. "What do you notice about my drawing?"
"It is a tree!" Rocket says. "The whole job is the root, and each part is a child."
"And each part is small enough to build in one sitting," Raven says.
Nova hums. "Here is a hint. Give each small part its own function."
To decompose a problem means to break it into smaller parts. Each part becomes one function with one job.
| Part | Job | Function |
|---|---|---|
| Count | Add up every supply | total_items(stock) |
| Low | List the supplies below a limit, in A to Z order | low_stock(stock, limit) |
| Find | Find an item in a sorted list of names, fast | find_item(names, target) |
| Crew | Count everyone in the command tree | count_crew(node) |
| Restock | Add more of a supply | restock(stock, item, amount) |
| Report | Print everything clearly | report(stock, tree) |
| Part | Job | Function |
|---|---|---|
| Questions | Store each question with its answer | make_quiz() |
| Ask | Show a question and read an answer | ask_one(question) |
| Check | Compare an answer with the right one | is_right(given, right) |
| Score | Add up the right answers | score(results) |
def is_right(given, right):
return given == right
def score(results):
total = 0
for r in results:
if r:
total = total + 1
return total
print(is_right("8", "8"))
print(is_right("9", "8"))
print(score([True, False, True, True])) | Statement | True or false? |
|---|---|
| is_right returns True or False. | ? |
| score counts the False values. | ? |
| The quiz plan has four parts. | ? |
| Decomposing turns one big job into a tree of small jobs. | ? |
Super decomposing! A big job is just small jobs in a tree. Tomorrow we choose the right container for each piece of data.