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.
x
is greater than or equal to the length of the list?
None
.Q: What if the list items
is empty?
None
since there are no valid indices.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`.
⚠️ Common Mistakes
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