← Back to course
Code Crew G5 / Week 06 / Friday
5/6
Week 06 Β· Search one by one

Friday

The search that gave up
// Linear search and counting checks
⏱ about 15 min

Friday: The search that gave up

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?"

The buggy version

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.

FIX THE BUG.
  • Read the question.
  • Tap your answer.
Where should return -1 go?
PUT THE FIXED FIND FUNCTION IN ORDER.
  • ? return -1
  • ? if items[i] == target:
  • ? for i in range(len(items)):
  • ? return i
  • ?def find(items, target):
WHY THIS EXERCISENot found can only be decided after the loop has checked every item.

Python's own search

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
What does print("Pip" in stars) show for this list?
WHY THIS EXERCISEin gives True only when the item is somewhere in the list.

Practice lab: the skipped star

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"))
What does find(stars, "Frost") return?
What does find(stars, "Ember") show?
Which spot does this buggy find skip?
To fix it, range should start at what number?
BUG CHECK
  • Read the question.
  • Tap your answer.
Why is this bug sneaky?
What does print("Frost" in stars) show?
What does stars.index("Frost") give?
StatementTrue 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.?
WHY THIS EXERCISETest the first, the last and a missing target every time.
For a missing target in this 3 star list, how many checks does the buggy find make?
WHY THIS EXERCISErange(1, 3) has two numbers, so only two checks happen.

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.

← Thursday