TIP102 Unit 1 Session 1 Standard (Click for link to problem statements)
Understand what the interviewer is asking for by using test cases and questions about the problem.
villain
is not found in the crowd
?
[]
.Q: How does the function handle multiple occurrences of the villain
in the crowd
?
villain
is found.The function find_villain(crowd, villain
) should return a list of indices where the villain
is found in the crowd
.
HAPPY CASE
Input: lst = ['Batman', 'The Joker', 'Alfred Pennyworth', 'Robin', 'The Joker', 'Catwoman', 'The Joker'], target = 'The Joker'
Expected Output: [1, 4, 6]
EDGE CASE
Input: lst = [], target = 'The Joker'
Expected Output: []
Input: lst = ['Batman', 'Superman'], target = 'The Joker'
Expected Output: []
Plan the solution with appropriate visualizations and pseudocode.
General Idea: Iterate through the crowd list, checking each element against the villain, and store the indices where they match.
1. Define the function `find_villain(crowd, villain)`.
2. Initialize an empty list `indices` to store matching indices.
3. Use a loop to iterate through `crowd` with an index counter.
4. For each person in `crowd`, check if they match `villain`.
5. If they match, append the current index to `indices`.
6. Return the `indices` list.
⚠️ Common Mistakes
Implement the code to solve the algorithm.
def find_villain(crowd, villain):
# Initialize an empty list to store the indices
indices = []
# Initialize the index counter
index = 0
# Iterate through the crowd list
for person in crowd:
# Check if the current person is the villain
if person == villain:
# If so, append the current index to the indices list
indices.append(index)
# Increment the index counter
index += 1
# Return the list of indices
return indices