Codepath

Thistle Hunt

TIP102 Unit 1 Session 1 Standard (Click for link to problem statements)

Problem Highlights

  • 💡 Difficulty: Easy
  • Time to complete: 5 mins
  • 🛠️ Topics: Lists, Loops

U-nderstand

Understand what the interviewer is asking for by using test cases and questions about the problem.

  • Q: What should the function return if the list items does not contain any "thistle"?
    • A: The function should return an empty list [].
  • Q: Should the function be case-sensitive when searching for "thistle"?

    • A: Yes, the function should be case-sensitive and only return indices of elements that exactly match "thistle".
  • The function locate_thistles() should take a list of strings items and return a list of the indices where the value is "thistle".

HAPPY CASE
Input: ["thistle", "stick", "carrot", "thistle", "eeyore's tail"]
Expected Output: [0, 3]

EDGE CASE
Input: ["book", "bouncy ball", "leaf", "red balloon"]
Expected Output: []

P-lan

Plan the solution with appropriate visualizations and pseudocode.

General Idea: Define a function that iterates through the list and records the indices where the value is "thistle".

1. Define the function `locate_thistles(items)`.
2. Initialize an empty list `indices` to store the indices.
3. Iterate through the list using a range to get both index and item.
4. For each item, check if it is equal to `"thistle"`.
5. If it is, add the index to `indices`.
6. Return the `indices` list.

⚠️ Common Mistakes

  • Not correctly iterating through all elements of the input list.
  • Misplacing or misidentifying the indices.

I-mplement

Implement the code to solve the algorithm.

def locate_thistles(items):
    # Initialize an empty list to store the indices
    indices = []
    
    # Iterate through the list using range to get both index and item
    for i in range(len(items)):
        # If the item is "thistle", add its index to the list
        if items[i] == "thistle":
            indices.append(i)
    
    # Return the list of indices
    return indices
Fork me on GitHub