Mission Control sends a message: please confirm that the star Halo is in your catalog.
Rocket scrolls the list so fast that the names blur. "I did not see it. Maybe it is not there?"
Raven slows the list down. "What do you notice if we read one name at a time, from the top?"
They read: Ember, Frost, Glow, Halo. "There it is!" Rocket says. "Spot 3."
Nova flickers. "Here is a hint. Write down the steps you just did. That is an algorithm."
Linear search checks each item in order. If an item matches the target, it returns that spot number.
If it checks every item and finds no match, it returns -1. That number means not found, because no spot is -1 here.
def find(items, target):
for i in range(len(items)):
if items[i] == target:
return i
return -1
stars = ["Ember", "Frost", "Glow", "Halo", "Iris"]
print(find(stars, "Glow"))
print(find(stars, "Zephyr")) Output: 2 -1
| Statement about find | True or false? |
|---|---|
| find checks the items starting from spot 0. | ? |
| find keeps checking after it finds the target. | ? |
| return -1 runs when the target is missing. | ? |
def find(items, target):
for i in range(len(items)):
if items[i] == target:
return i
return -1
moons = ["Ash", "Bay", "Cove", "Bay"]
print(find(moons, "Bay"))
print(find(moons, "Cove"))
print(find(moons, "Dune")) | Statement | True or false? |
|---|---|
| find(moons, "Cove") checks three items. | ? |
| find returns the name it found. | ? |
| return -1 runs only after the loop ends. | ? |
| A list can hold the same name twice. | ? |
Great searching! Tomorrow we count how many checks a search takes.