Linear search
Python · Unit 23: Searching and sorting
- Full plan
- Python
- 9 exercises
Searching is answering where something is. The most direct way is to look one by one, from start to end, until you find it.
That is called linear search, and it works with any list, sorted or not.
prices = [40, 15, 70, 15]
for i, p in enumerate(prices):
if p == 70:
print("it is at", i)Prints
it is at 2
The rest of the explanation is in the lesson, which is part of the full plan.
Exercises in this lesson
You do them in the app, which checks them on the spot and explains why.
1. Predict the output
What does this code print?
2. Predict the output
What does this code print?
3. Find the bug
searchshould return the position of the 7, which is 1, but it prints -1. Which line has the error?4. Complete the code
Complete it so it reports when the value is not there.
5. Predict the output
The 5 is not in the list. What does it print?
6. Multiple choice
When
numsis a list, what does9 in numshave to do under the hood?7. Find the case that fails
position(nums, v)should return the position ofv, or -1 ifvis not in the list. Which call breaks it?8. Put the lines in order
Build the function that gives the position of the first negative number.
9. Predict the output
What does this code print?
It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.