5 Best Ways to Find the Sum of All Even and Odd Digits of an Integer List in Python

πŸ’‘ Problem Formulation: We want to create a Python program that processes an integer list and calculates two sums: one for all the even digits, and another for all the odd digits found within the numbers of the list. For example, given the list [12, 34, 56], the sum of even digits would be 2+4+6 = 12 and the sum of odd digits would be 1+3+5 = 9.

Method 1: Using Loops and Modulo Operator

This method involves iterating through each number in the list, extracting its digits, and using the modulo operator to determine whether a digit is even or odd before adding it to the respective sum. This is a hands-on, basic approach that works well for small lists.

Here’s an example:

def sum_even_odd_digits(numbers):
    even_sum = odd_sum = 0
    for number in numbers:
        for digit in str(number):
            if int(digit) % 2 == 0:
                even_sum += int(digit)
            else:
                odd_sum += int(digit)
    return even_sum, odd_sum

print(sum_even_odd_digits([12, 34, 56]))

Output: (12, 9)

This snippet defines the function sum_even_odd_digits() which takes a list of numbers as input. It iterates over every number and its digits, using modulo to check for evenness, and accumulates the sum in even_sum or odd_sum accordingly.

Method 2: Using List Comprehension and Modulo Operator

The second method simplifies the code using list comprehension to create a flat list of all digits, which are then filtered and summed based on their evenness or oddness. This is a more Pythonic and succinct approach.

Here’s an example:

def sum_even_odd_digits(numbers):
    digits = [int(digit) for number in numbers for digit in str(number)]
    even_sum = sum(digit for digit in digits if digit % 2 == 0)
    odd_sum = sum(digit for digit in digits if digit % 2 != 0)
    return even_sum, odd_sum

print(sum_even_odd_digits([12, 34, 56]))

Output: (12, 9)

In this snippet, we generate a list of all digits then use list comprehension with a condition to either include even or odd digits, and subsequently pass them to the sum() function to get our desired sums.

Method 3: Using Functional Programming with map and filter

This method takes advantage of Python’s functional programming capabilities by applying map() and filter() functions to categorize and sum digits. This offers clean and modular code for better readability.

Here’s an example:

def sum_even_odd_digits(numbers):
    digits = list(map(int, ''.join(map(str, numbers))))
    even_sum = sum(filter(lambda x: x % 2 == 0, digits))
    odd_sum = sum(filter(lambda x: x % 2 != 0, digits))
    return even_sum, odd_sum

print(sum_even_odd_digits([12, 34, 56]))

Output: (12, 9)

The code defines a function that first converts all numbers to a string, joins them, and then maps them to integers. It then uses filter() to separate even and odd digits and sums them up.

Method 4: Using Regular Expressions

Regular expressions can be applied to filter out all even and odd digits in one sweep before summing them. This method is more advanced and can be very efficient, but it may be less readable for those not familiar with regular expressions.

Here’s an example:

import re

def sum_even_odd_digits(numbers):
    all_digits = ''.join(map(str, numbers))
    even_digits = re.findall('[24680]', all_digits)
    odd_digits = re.findall('[13579]', all_digits)
    return sum(map(int, even_digits)), sum(map(int, odd_digits))

print(sum_even_odd_digits([12, 34, 56]))

Output: (12, 9)

This function concatenates all numbers into a string and uses the re.findall() method to create lists of even and odd digits, which are then mapped to integers and summed.

Bonus One-Liner Method 5: Using Generator Expressions

For those who appreciate conciseness, this one-liner employs generator expressions within the sum function to provide a terse yet powerful solution.

Here’s an example:

print(
    (
        sum(int(d) for n in [12, 34, 56] for d in str(n) if int(d) % 2 == 0),
        sum(int(d) for n in [12, 34, 56] for d in str(n) if int(d) % 2 != 0)
    )
)

Output: (12, 9)

This one-liner directly prints a tuple where sums are computed using generator expressions that iterate over each digit and check their parity while summing them.

Summary/Discussion

  • Method 1: Loop with Modulo. Easy to understand. Can be slow with large lists.
  • Method 2: List Comprehension. Pythonic and more concise. Still not the fastest for very large lists.
  • Method 3: Functional Programming. Clean and modular. Potentially unfamiliar syntax for some.
  • Method 4: Regular Expressions. Efficient and compact. Less readable and overkill for simple tasks.
  • Method 5: One-Liner. Very concise. May sacrifice readability for brevity and can be tricky to debug.