Grades array setup
- Algorithms course
- Beginner
- Lesson 18/80
- 4 min
Define the grades array and print it.
Add search function
Now we add the find_note(notes, target) function. It uses linear search to find the target note's index.
The function returns -1 if the note is not found. This is a standard value to indicate search failure.
Using linear search
The find_note function can access the note array by calling init_notes defined in the previous lesson.
This shows the power of cumulative code: new functions build on old ones and nothing is rewritten.
Practice Search function
Write find_note(notes, target). Return index of target; -1 if absent. Print 3 with print(find_note(init_notes(), 92)).
Starter code
def init_notes():
# Return note array
return [85, 90, 78, 92, 88]
def find_note(notes, target):
# Search for targetSample solution
def init_notes():
# Return note array
return [85, 90, 78, 92, 88]
def find_note(notes, target):
# Search for target
for i in range(len(notes)):
if notes[i] == target:
return i
return -1
print(find_note(init_notes(), 92))Expected output
3
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does find_note return if not found?
- -1 Correct answer
- 1
- 0
- n
Explanation: find_note returns -1.
2 Function parameter
find_note(notes, ____) — target note
find_note(notes, target) — target note
Explanation: target is right.
3 Grades array setup: match the terms
| Term | Meaning |
|---|---|
find_note |
Search |
notes |
Array |
target |
Target |
-1 |
Not found |