- 
                Notifications
    You must be signed in to change notification settings 
- Fork 266
Return Item
        LeWiz24 edited this page Aug 27, 2024 
        ·
        4 revisions
      
    TIP102 Unit 1 Session 1 Standard (Click for link to problem statements)
- 💡 Difficulty: Easy
- ⏰ Time to complete: 5 mins
- 🛠️ Topics: List Indexing, Return Statements
Understand what the interviewer is asking for by using test cases and questions about the problem.
- 
Q: What if the index xis greater than or equal to the length of the list?- A: The function should return None.
 
- A: The function should return 
- 
Q: What if the list itemsis empty?- A: The function should return Nonesince there are no valid indices.
 
- A: The function should return 
- 
The function get_item()should take a list items and an integer x, and return the element at index x if it is a valid index. If x is not a valid index, the function should return None.
HAPPY CASE
Input: items = ["piglet", "pooh", "roo", "rabbit"], x = 2
Expected Output: "roo"
Input: items = ["piglet", "pooh", "roo", "rabbit"], x = 0
Expected Output: "piglet"
EDGE CASE
Input: items = ["piglet", "pooh", "roo", "rabbit"], x = 5
Expected Output: None
Plan the solution with appropriate visualizations and pseudocode.
General Idea: Define a function that checks if the provided index is valid and returns the corresponding element if it is, or None if it isn't.
1. Define the function `get_item(items, x)`.
2. Check if `x` is within the valid range of indices for `items`.
3. If `x` is valid, return the element at index `x`.
4. If `x` is not valid, return `None`.- Forgetting to check if x is within the valid range.
- Not handling negative values for x.
Implement the code to solve the algorithm.
def get_item(items, x):
    # Check if x is within the valid range
    if 0 <= x < len(items):
        return items[x]
    else:
        return None