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.
items
does not contain any "thistle"
?
[]
.Q: Should the function be case-sensitive when searching for "thistle"
?
"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: []
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
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