Editor

Fix the Early Exit

Beginner · Fix the bug · from Linear Search and Binary Search: Counting the Checks

From the lesson: Linear Search and Binary Search: Counting the Checks

Searching a list means checking elements until you find the one you want, and the method you choose decides whether that takes 3 checks or 3 million. Linear search works on any list. Binary search is far faster on big lists, but it only works when the data is sorted.

Read the lesson

This linear search should return True when target is anywhere in the list. But contains([4, 8, 15], 15) returns False. Find the bug and fix it.

def contains(items, target):
for item in items:
if item == target:
return True
else:
return False
return False

What Check runs

Your code runs first, then each of these lines, and 2 more that stay hidden. The output must match exactly.

RunsExpected output
contains([4, 8, 15], 15)True
contains([4, 8, 15], 9)False

More Linear and Binary Search exercises

All Python exercises · 50 practice problems