- 
                Notifications
    
You must be signed in to change notification settings  - Fork 266
 
Find the Villain
        Andrew Burke edited this page Jan 13, 2025 
        ·
        1 revision
      
    TIP102 Unit 1 Session 1 Standard (Click for link to problem statements)
- 💡 Difficulty: Easy
 - ⏰ Time to complete: 5 mins
 - 🛠️ Topics: Functions, Lists, Loops
 
Understand what the interviewer is asking for by using test cases and questions about the problem.
- 
Q: What should the function return if the
villainis not found in thecrowd?- A: The function should return an empty list 
[]. 
 - A: The function should return an empty list 
 - 
Q: How does the function handle multiple occurrences of the
villainin thecrowd?- A: The function should return a list of all indices where the 
villainis found. 
 - A: The function should return a list of all indices where the 
 - 
The function
find_villain(crowd, villain) should return a list of indices where thevillainis found in thecrowd. 
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.- Forgetting to initialize the indices list.
 - Not incrementing the index counter correctly.
 
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