-
Notifications
You must be signed in to change notification settings - Fork 244
Return Item
Raymond Chen edited this page Aug 1, 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.
- Established a set (2-3) of test cases to verify their own solution later.
- Established a set (1-2) of edge cases to verify their solution handles complexities.
- Have fully understood the problem and have no clarifying questions.
- Have you verified any Time/Space Constraints for this problem?
- 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