Linear search checks items from the start until it finds the target or runs out. It works on an unsorted list. Worst case is n comparisons.
Goal
Return the index and the step count. Print a hit and a miss.
The loop
def linear_search(items, target):
steps = 0
for i, item in enumerate(items):
steps += 1
if item == target:
return i, steps
return -1, steps
cities = ["Nairobi", "Mombasa", "Kisumu", "Nakuru"]
print(linear_search(cities, "Kisumu"))
print(linear_search(cities, "Eldoret"))Index 2 for Kisumu after 3 steps. -1 for a miss after 4 steps.
First match
def linear_search(items, target):
steps = 0
for i, item in enumerate(items):
steps += 1
if item == target:
return i, steps
return -1, steps
prices = [10.5, 22.0, 10.5, 31.0]
print(linear_search(prices, 10.5))Duplicates: you get the first index.
From a file
Download cities.txt, Add files, then:
from pathlib import Path
def linear_search(items, target):
steps = 0
for i, item in enumerate(items):
steps += 1
if item == target:
return i, steps
return -1, steps
cities = Path("cities.txt").read_text(encoding="utf-8").splitlines()
print(cities)
print(linear_search(cities, "Nakuru"))Pitfall
Python’s list.index raises ValueError on a miss. Returning -1 plus a step count makes the algorithm visible.