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.
nums
is empty?
[]
.Q: How does the function determine if a number is odd?
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: []
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
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