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

Tuesday

Count the checks
// Linear search and counting checks
⏱ about 15 min

Tuesday: Count the checks

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

Counting each check

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.

TargetSpotChecks
Ember01
Halo34
Lumen??
Pip??
How many checks to find Lumen?
How many checks to find Pip?
How many checks for a missing star like Zephyr?
USE FIND_COUNT WITH THE EIGHT STARS.
  • Read the question.
  • Tap your answer.
Which target needs the fewest checks?
How many checks to find Juno?

Practice lab: six moons

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"))
How many checks to find Ash?
How many checks to find Fern?
How many checks for a missing moon?
What spot is Dune in?
CHECK COUNT
  • Read the question.
  • Tap your answer.
How many checks to find Bay?
Which moon takes exactly 3 checks?
A list has 100 moons. How many checks for a missing one?
StatementTrue 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.?
WHY THIS EXERCISEWhere the target sits decides how long linear search takes.
A target sits in spot 9. How many checks does linear search need?
WHY THIS EXERCISESpots 0 through 9 are all checked. That is 10 checks.

Nice counting! Counting steps is how engineers measure an algorithm. Tomorrow we find the best and worst cases.

← Monday