Card 11: Linear Search

Module 4: Data Structures

1 The Hook

You're looking for your favorite song in a playlist.

You scroll down, checking each title one by one until you find it.

This is a Linear Search. Start at the top, check, move, check, move... until found.

2 Worked Example

Finding "Nemo" in a tank.

fish = ["Dory", "Nemo", "Bruce"]
for f in fish:
if f == "Nemo":
print("Found him!")

Pattern 2: Counting

count = 0
for f in fish:
if f == "Nemo":
count = count + 1

PREDICT

What does this code output?

nums = [10, 20, 30, 40]
for x in nums:
  if x > 25:
    print(x)
    break

Interactive Editor

> _
BRONZE (MODIFY)

🥉 Golden Ticket

1. Create tickets = ["Red", "Gold", "Blue"].
2. Search for "Gold".
3. If found, print "Winner!".

> _
SILVER (FIX)

🥈 Too Much Noise

This code is annoying! It prints "Not Found" for every single person who isn't Waldo.
1. Remove the else part entirely.
2. It should ONLY print "Ref Found" if found.

> _
GOLD (MAKE)

🥇 Count The Admins

1. Create users = ["Admin", "Guest", "Root", "Admin"].
2. Create a variable count = 0.
3. Loop through the list. If user is "Admin", add 1 to count.
4. Print the final count (Should be 2).

> _