Codepath

Return Item

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

Problem Highlights

  • 💡 Difficulty: Easy
  • Time to complete: 5 mins
  • 🛠️ Topics: List Indexing, Return Statements

U-nderstand

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

  • Q: What if the index x is greater than or equal to the length of the list?
    • A: The function should return None.
  • Q: What if the list items is empty?

    • A: The function should return 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

P-lan

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

  • Forgetting to check if x is within the valid range.
  • Not handling negative values for x.

I-mplement

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
Fork me on GitHub