Odd - codepath/compsci_guides GitHub Wiki

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

Problem Highlights

  • 💡 Difficulty: Easy
  • Time to complete: 5 mins
  • 🛠️ Topics: Functions, Lists, Loops

U-nderstand

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

  • Q: What should the function return if the input list nums is empty?

    • A: The function should return an empty list [].
  • Q: How does the function determine if a number is odd?

    • A: The function checks if a number is odd by using modulus division (num % 2 != 0).
  • The function get_odds(nums) should return a new list containing all the odd numbers from the input list nums.

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

Input: [2, 4, 6, 8]
Expected Output: []

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

Input: [2, 4, 6, 8]
Expected Output: []

P-lan

Plan the solution with appropriate visualizations and pseudocode.

General Idea: Iterate through the nums list and use modulus division to check if each number is odd, then store the odd numbers in a new list.

1. Define the function `get_odds(nums)`.
2. Initialize an empty list `odd_numbers` to store odd numbers.
3. Use a loop to iterate through each number in `nums`.
4. For each number, check if it is odd using modulus division.
5. If it is odd, append it to the `odd_numbers` list.
6. Return the `odd_numbers` list.

⚠️ Common Mistakes

  • Forgetting to initialize the odd_numbers list.
  • Incorrectly checking for odd numbers (ensure to use num % 2 != 0).

I-mplement

Implement the code to solve the algorithm.

def get_odds(nums):
    # Initialize an empty list to store the odd numbers
    odd_numbers = []
    
    # Iterate through the list of numbers
    for num in nums:
        # Check if the number is odd
        if num % 2 != 0:
            # If so, append it to the odd_numbers list
            odd_numbers.append(num)
    
    # Return the list of odd numbers
    return odd_numbers