The supply officer has one wish. She wants the tracker to list what is running low, A to Z.
Rocket starts sorting by hand. "Lamps, rope," he mutters. Then he stops himself and smiles.
"What do you notice?" Raven asks. "You already know a tool for that."
"sorted()!" Rocket says. "And a loop with an if to pick the low ones."
Nova blinks. "Here is a hint. Collect the low ones in a list first. Then sort them at the end."
# Part 3: what is running low?
def low_stock(stock, limit):
low = []
for item in stock:
if stock[item] < ____:
low.append(item)
return ____(low)
inventory = {
"water": 40,
"seeds": 12,
"lamps": 3,
"maps": 7,
"rope": 2,
"tools": 15,
}
def low_stock(stock, limit):
low = []
for item in stock:
if stock[item] < limit:
low.append(item)
return sorted(low)
print(low_stock(inventory, 5))
print(low_stock(inventory, 10))
print(low_stock({}, 5)) Output: ['lamps', 'rope'] ['lamps', 'maps', 'rope'] []
| Statement about low_stock | True or false? |
|---|---|
| It returns the names, not the counts. | ? |
| An empty dictionary makes it crash. | ? |
| The list comes back in A to Z order. | ? |
def low_stock(stock, limit):
low = []
for item in stock:
if stock[item] < limit:
low.append(item)
return sorted(low)
stock = {"tape": 9, "maps": 1, "fuel": 4}
print(low_stock(stock, 5))
print(low_stock(stock, 1))
print(low_stock(stock, 100)) | Statement | True or false? |
|---|---|
| low_stock(stock, 1) returns an empty list. | ? |
| maps is low with a limit of 1. | ? |
| The limit is a parameter, so it can change each call. | ? |
| low_stock does not change the stock dictionary. | ? |
Part 3 done and tested! Tomorrow we add a fast way to find any supply.