-
Notifications
You must be signed in to change notification settings - Fork 0
Hunny Hunt
TIP102 Unit 1 Session 1 Advanced (Click for link to problem statements)
- 💡 Difficulty: Easy
- ⏰ Time to complete: 5 mins
- 🛠️ Topics: Lists, Linear Search, Iteration
Understand what the interviewer is asking for by using test cases and questions about the problem.
-
Q: What is the input to the function?
- A: The input is a list
items
and atarget
value that needs to be found in the list.
- A: The input is a list
-
Q: What is the expected output of the function?
- A: The function should return the first index of
target
in the listitems
, and-1
iftarget
is not found.
- A: The function should return the first index of
-
Q: Are there any constraints or special conditions?
- A: The function should not use any built-in functions and should handle all types of elements that might be in the list.
-
Q: What if the list is empty?
- A: If the list is empty, the function should return
-1
.
- A: If the list is empty, the function should return
-
The function
linear_search()
should take a list of items and atarget
value, returning the first index of target initems
. If target is not found, it should return -1. Built-in functions should not be used.
HAPPY CASE
Input: items = ['haycorn', 'haycorn', 'haycorn', 'hunny'], target = 'hunny'
Expected Output: 3
Input: items = ['bed', 'blue jacket', 'red shirt', 'hunny'], target = 'red balloon'
Expected Output: -1
EDGE CASE
Input: items = [], target = 'hunny'
Expected Output: -1
Input: items = ['hunny'], target = 'hunny'
Expected Output: 0
Plan the solution with appropriate visualizations and pseudocode.
General Idea: Use a ranged for loop to iterate through the list, checking each element against the target.
1. Define the function `linear_search(items, target)`.
2. Iterate through the list using a ranged for loop based on the length of `items`.
3. For each index, check if the current element matches the target.
4. If a match is found, return the index.
5. If the loop completes without finding a match, return -1.
- Forgetting to handle the case of an empty list.
- Not returning the index for the first occurrence of the target.
Implement the code to solve the algorithm.
def linear_search(items, target):
# Iterate through the list with a ranged for loop
for index in range(len(items)):
# Check if the current element matches the target
if items[index] == target:
return index # Return the index if target is found
# If target is not found, return -1
return -1