Codepath

Pairs

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

Problem Highlights

  • 💡 Difficulty: Easy
  • Time to complete: 5 mins
  • 🛠️ Topics: List Iteration, Conditionals

U-nderstand

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

  • Q: What if the list item_quantities is empty?
    • A: The function should return True because there are no quantities that are odd.
  • Q: What happens if one or more of the numbers in the list is odd?

    • A: The function should return False since Rabbit only wants to own an even number of each item.
  • The function can_pair() should take a list of integers item_quantities and return True if every number in the list is even, otherwise return False.

HAPPY CASE
Input: [2, 4, 6, 8]
Expected Output: True

EDGE CASE
Input: [1, 2, 3, 4]
Expected Output: False

Input: []
Expected Output: True

P-lan

Plan the solution with appropriate visualizations and pseudocode.

General Idea: Define a function that iterates through the list and checks if each number is even.

1. Define the function `can_pair(item_quantities)`.
2. Iterate through each quantity in the list `item_quantities`.
3. Check if the quantity is odd using the modulo operator (`quantity % 2 != 0`).
4. If any quantity is odd, return `False`.
5. If no odd quantities are found, return `True`.

⚠️ Common Mistakes

  • Forgetting to handle the empty list case, which should return True.

I-mplement

Implement the code to solve the algorithm.

def can_pair(item_quantities):
    # Iterate through each quantity in the list
    for quantity in item_quantities:
        # Check if the quantity is odd
        if quantity % 2 != 0:
            return False
    # If no odd quantities are found, return True
    return True
Fork me on GitHub