Function returns index 2 immediately when target found.
Final Answer:
2 -> Option A
Quick Check:
Index of 7 in list = 2 [OK]
Hint: Return index when target matches during loop [OK]
Common Mistakes:
Returning element value instead of index
Returning -1 even when target is present
Confusing index with element value
4. Find the error in this linear search function:
def linear_search(arr, target):
for i in range(len(arr)):
if arr[i] = target:
return i
return -1
medium
A. Using '=' instead of '==' in the if condition
B. Missing colon ':' after for loop
C. Returning -1 instead of None when not found
D. Looping over range(len(arr)) instead of arr
Solution
Step 1: Identify syntax error in condition
The if condition uses '=' which is assignment, not comparison.
Step 2: Correct operator for comparison
Use '==' to compare values in if condition.
Final Answer:
Using '=' instead of '==' in the if condition -> Option A
Quick Check:
Comparison needs '==' not '=' [OK]
Hint: Use '==' for comparison, '=' is assignment [OK]
Common Mistakes:
Using single '=' in if condition
Confusing assignment and comparison operators
Ignoring syntax errors causing runtime failure
5. You want to find all positions of a target number in a list using linear search. Which modification to the code below will achieve this?
def linear_search_all(arr, target):
positions = []
for i in range(len(arr)):
if arr[i] == target:
# What to do here?
return positions
print(linear_search_all([1, 3, 7, 3, 9, 3], 3))
hard
A. Return i immediately when target is found
B. Append index i to positions list inside the if block
C. Break the loop after first match
D. Use positions = target instead of list
Solution
Step 1: Understand requirement to find all matches
We must collect all indices where target appears, not stop at first.
Step 2: Append matching indices to list
Inside if, add positions.append(i) to store all found positions.
Final Answer:
Append index i to positions list inside the if block -> Option B
Quick Check:
Collect all indices by appending [OK]
Hint: Append all matching indices to list [OK]
Common Mistakes:
Returning immediately on first match
Breaking loop early
Assigning target to positions instead of appending
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.