Print the result
- Algorithms course
- Beginner
- Lesson 20/80
- 4 min
Print found/not-found based on the search result.
Find all occurrences
In the final step we add find_all(notes, target). It collects all positions of the target in the array.
We add each match's index to a result array. This is useful to check if a note appears for more than one student.
Project complete
You now have a working note search application: init_notes gives the array, find_note searches, report_result prints, find_all finds all occurrences.
Each function was built on top of the previous one. This is the cumulative approach used in real-world software development.
Practice Find all occurrences
Write find_all(notes, target). Collect all indices of target in an array and print them. Call find_all([85, 92, 78, 92], 92) to print 1, 3.
Starter code
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
def report_result(notes, target):
# Print result
idx = find_note(notes, target)
if idx >= 0:
print(idx)
else:
print('yok')
def find_all(notes, target):
# Find all indicesSample 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
def report_result(notes, target):
# Print result
idx = find_note(notes, target)
if idx >= 0:
print(idx)
else:
print('yok')
def find_all(notes, target):
# Find all indices
result = []
for i in range(len(notes)):
if notes[i] == target:
result.append(i)
for idx in result:
print(idx)
find_all([85, 92, 78, 92], 92)Expected output
1 3
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Print the result: match the terms
| Term | Meaning |
|---|---|
find_all |
Find all |
result |
Result array |
append |
Add |
print |
2 What does find_all return?
- Single index
- Error
- Array of indices Correct answer
- A note
Explanation: find_all returns an array of indices.
3 Collection
Each match is added to the result array with ____().
Each match is added to the result array with append().
Explanation: append is right.