Tutorialspoint
Problem
Solution
Submissions

Compute the Sum of Even and Odd Numbers in a List

Certification: Basic Level Accuracy: 74.47% Submissions: 47 Points: 10

Write a Python program that computes the sum of even numbers and the sum of odd numbers in a given list separately.

Example 1
  • Input: numbers = [1, 2, 3, 4, 5, 6]
  • Output: Even sum: 12, Odd sum: 9
  • Explanation:
    • Step 1: Initialize even_sum = 0 and odd_sum = 0.
    • Step 2: Iterate through each number in the list.
    • Step 3: For each number, check if it's even (divisible by 2) or odd.
    • Step 4: Even numbers: 2, 4, 6. Sum = 2 + 4 + 6 = 12.
    • Step 5: Odd numbers: 1, 3, 5. Sum = 1 + 3 + 5 = 9.
    • Step 6: Return both sums: Even sum: 12, Odd sum: 9.
Example 2
  • Input: numbers = [8, 10, 12, 15, 17, 20]
  • Output: Even sum: 50, Odd sum: 32
  • Explanation:
    • Step 1: Initialize even_sum = 0 and odd_sum = 0.
    • Step 2: Iterate through each number in the list.
    • Step 3: For each number, check if it's even (divisible by 2) or odd.
    • Step 4: Even numbers: 8, 10, 12, 20. Sum = 8 + 10 + 12 + 20 = 50.
    • Step 5: Odd numbers: 15, 17. Sum = 15 + 17 = 32.
    • Step 6: Return both sums: Even sum: 50, Odd sum: 32.
Constraints
  • 1 ≤ list_length ≤ 10^6
  • -10^9 ≤ list[i] ≤ 10^9
  • Time Complexity: O(n) where n is the length of the list
  • Space Complexity: O(1)
ArraysNumberListFacebookHCL Technologies
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Initialize two variables to store the sum of even and odd numbers
  • Use the modulo operator(%) to check each number's parity

Steps to solve by this approach:

 Step 1: Initialize two variables to track the sum of even numbers and the sum of odd numbers.

 Step 2: Iterate through each number in the input list.
 Step 3: Check if the current number is even or odd using the modulo operator.
 Step 4: If the number is even (divisible by 2), add it to the even sum.
 Step 5: If the number is odd (not divisible by 2), add it to the odd sum.
 Step 6: Return a tuple containing both the even sum and odd sum.

Submitted Code :