Rocket tidies his find function. He adds an else so it looks neater.
Now find(stars, "Glow") returns -1. "But Glow is right there in spot 2!" Rocket says.
Raven traces it with her finger. "What do you notice about how many stars it checks?"
"Just one!" Rocket says. "Ember does not match, so it gives up."
Nova shines on the else. "Let's debug together. Here is a hint. When should a search say not found?"
def find(items, target):
for i in range(len(items)):
if items[i] == target:
return i
else:
return -1
stars = ["Ember", "Frost", "Glow", "Halo"]
print(find(stars, "Glow"))
print(find(stars, "Ember")) Output: -1 0
On the first pass, Ember does not match, so the else runs return -1. The function ends after one check.
It only works when the target is in spot 0. That is why testing more than one target matters.
Python can search a list for you. The word in checks the items one by one and gives True or False. The index() tool gives the spot.
stars = ["Ember", "Frost", "Glow", "Halo"]
print("Glow" in stars)
print(stars.index("Glow")) Output: True 2
def find(items, target):
for i in range(1, len(items)):
if items[i] == target:
return i
return -1
stars = ["Ember", "Frost", "Glow"]
print(find(stars, "Glow"))
print(find(stars, "Ember")) | Statement | True or false? |
|---|---|
| The buggy find checks spot 0. | ? |
| find(stars, "Glow") still gives the right answer. | ? |
| Testing the first item would catch this bug. | ? |
| range(len(items)) starts at 0. | ? |
Week 6 complete! You can search, count checks, name the best and worst cases and fix a search bug. Next week we search much faster.