← Back to course
Code Crew G5 / Week 12 / Tuesday
2/6
Week 12 Β· Ship it

Tuesday

Running low
// Build, test and graduate
⏱ about 15 min

Tuesday: Running low

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?

# Part 3: what is running low?
def low_stock(stock, limit):
    low = []
    for item in stock:
        if stock[item] < ____:
            low.append(item)
    return ____(low)
First blank: compare with
Second blank: which tool puts the list in A to Z order?

Test drive

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']
[]
CHANGE THE LIMIT.
  • Read the question.
  • Tap your answer.
What does low_stock(inventory, 3) return?
What does low_stock(inventory, 13) return first?
Statement about low_stockTrue or false?
It returns the names, not the counts.?
An empty dictionary makes it crash.?
The list comes back in A to Z order.?
WHY THIS EXERCISETesting the edge case shows the function handles an empty stock safely.

Practice lab: a new stock list

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))
How many names are in the first line?
What does the second line show?
How many names are in the third line?
What is the first name in the third line?
LOW CHECK
  • Read the question.
  • Tap your answer.
Why does low_stock call sorted() at the end?
What does low_stock(stock, 5) return?
What does low_stock(inventory, 4) return?
StatementTrue 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.?
WHY THIS EXERCISEParameters let one helper answer many questions.
How many names does low_stock(inventory, 16) return?
WHY THIS EXERCISElamps, maps, rope, seeds and tools are all under 16.

Part 3 done and tested! Tomorrow we add a fast way to find any supply.

← Monday