The catalog is growing fast. It now has eight stars, and Rocket keeps searching it.
"Some searches feel quick, and some feel slow," Rocket says. "Why?"
Raven taps the screen. "What do you notice about where each target sits in the list?"
"Hmm. Ember is at the very start," Rocket says. "Pip is all the way at the end."
Nova projects a counter. "Here is a hint. Count every check, and the pattern will show itself."
This version adds 1 to checks every time it compares an item. It prints the count before it returns.
def find_count(items, target):
checks = 0
for i in range(len(items)):
checks = checks + 1
if items[i] == target:
print("checks:", checks)
return i
print("checks:", checks)
return -1
stars = ["Ember", "Frost", "Glow", "Halo", "Iris", "Juno", "Lumen", "Pip"]
print(find_count(stars, "Halo")) Output: checks: 4 3
Halo is in spot 3, but the search needed 4 checks. Spots start at 0, but checks start at 1.
| Target | Spot | Checks |
|---|---|---|
| Ember | 0 | 1 |
| Halo | 3 | 4 |
| Lumen | ? | ? |
| Pip | ? | ? |
def find_count(items, target):
checks = 0
for i in range(len(items)):
checks = checks + 1
if items[i] == target:
print("checks:", checks)
return i
print("checks:", checks)
return -1
moons = ["Ash", "Bay", "Cove", "Dune", "Echo", "Fern"]
print(find_count(moons, "Echo")) | Statement | True or false? |
|---|---|
| The program prints checks: 5 for Echo. | ? |
| Spots start at 1. | ? |
| Moons near the front are found faster. | ? |
| A missing moon takes the most checks. | ? |
Nice counting! Counting steps is how engineers measure an algorithm. Tomorrow we find the best and worst cases.