Retrieve
Explain how a stack and a queue differ. Then predict the result of traversing a Python list by index.
Find the first matching value by checking items in order. Revisit the lesson and practise the stopping condition.
Check values in order; stop at the first match.
1def linear_search(items, target):2 for index in range(len(items)):3 if items[index] == target:4 return index5 return -1 The first item is the best case, O(1). The last item or an absent target takes O(n) time. This implementation uses O(1) auxiliary space.
Explain how a stack and a queue differ. Then predict the result of traversing a Python list by index.
Use numbers = [7, 3, 9, 2, 6] and target = 9. Describe how you would find the value without using in or index().
Track the index, current value, comparison and result. Compare stopping at the first match with continuing to the end.
Write find_first(items, target). Return the first matching index; return -1 only after all candidates have been checked. Test [], [4], and [4, 7, 4] with present and absent targets.
Explain best and worst cases. Count comparisons when the target is first, last or absent. Describe what changes if the data is sorted.
Spend about 3 minutes on each during practice time. Predict, run, change one thing, then explain. These prompts do not add homework.
A starter is runnable code to explore or complete. If the playground restores your saved code, the linked starter is selected in Example: use Load example when ready. Download your work before confirming replacement.
Complete the first-match search. Try a missing target and an empty list.
No imports needed.
break exits the loop; indices start at 0. Predict before running.
# break exits the loop; indices start at 0.
values = [7, 3, 9, 3]
target = 3
result = -1
for i in range(len(values)):
if values[i] == target:
result = i
break
print(result)
Count the comparisons until a match. Try a target at the beginning, end and absent.
No imports needed.
Change one value, predict the output, then run and explain any difference.
# Add one to the counter for each comparison.
values = [7, 3, 9]
target = 9
checks = 0
for value in values:
checks += 1
if value == target:
break
print(checks)
Why must return -1 come after the loop rather than after the first failed comparison?