-
Notifications
You must be signed in to change notification settings - Fork 242
Up and Down
LeWiz24 edited this page Aug 27, 2024
·
2 revisions
TIP102 Unit 1 Session 1 Standard (Click for link to problem statements)
- 💡 Difficulty: Easy
- ⏰ Time to complete: 5 mins
- 🛠️ Topics: Lists, Loops, Counting
Understand what the interviewer is asking for by using test cases and questions about the problem.
-
Q: What should the function return if the list is empty?
- A: The function should return
0
since there are no numbers to count.
- A: The function should return
-
Q: How does the function handle the counting of odd and even numbers?
- A: The function increments counters for odd and even numbers as it iterates through the list.
-
The function
up_and_down(lst)
should return the difference between the number of odd numbers and the number of even numbers in the list.
HAPPY CASE
Input: lst = [1, 2, 3]
Expected Output: 1
Input: lst = [1, 3, 5]
Expected Output: 3
Input: lst = [2, 4, 10, 2]
Expected Output: -4
EDGE CASE
Input: []
Expected Output: 0
Input: [3]
Expected Output: 1
Input: [2]
Expected Output: -1
Plan the solution with appropriate visualizations and pseudocode.
General Idea: Iterate through the lst list, count the odd and even numbers, and then return the difference.
1. Define the function `up_and_down(lst)`.
2. Initialize counters `odd_count` and `even_count` to 0.
3. Use a loop to iterate through each number in `lst`.
4. For each number, check if it is odd or even using modulus division.
5. Increment the appropriate counter based on the result.
6. Calculate the difference by subtracting `even_count` from `odd_count`.
7. Return the difference.
- Forgetting to initialize the counters.
- Incorrectly calculating the difference.
Implement the code to solve the algorithm.
def up_and_down(lst):
# Initialize counters for odd and even numbers
odd_count = 0
even_count = 0
# Iterate through the list of numbers
for num in lst:
# Check if the number is odd
if num % 2 != 0:
odd_count += 1
else:
even_count += 1
# Calculate the difference between odd and even counts
difference = odd_count - even_count
# Return the difference
return difference