Checking Divisibility of Even-Place Digits Product by Odd-Place Digits Sum in Python

Rate this post

πŸ’‘ Problem Formulation: This article explores how to ascertain if a number’s even-positioned digit product is divisible by the sum of its odd-positioned digits in Python. For instance, given the number 123456, the product of the digits in even places (2, 4, 6) is 48, and the sum of digits in odd places (1, 3, 5) is 9. We want to check if 48 is divisible by 9.

Method 1: Iterative Approach using Loops

This method uses simple iterative loops to traverse the digits of the number at even and odd positions, calculate the product and sum respectively, and then checks for divisibility. This is a straightforward approach that leverages the basic constructs of the Python language.

Here’s an example:

def is_divisible(number):
    str_num = str(number)
    product_even = 1
    sum_odd = 0
    for i in range(len(str_num)):
        if i % 2 == 0:
            sum_odd += int(str_num[i])
        else:
            product_even *= int(str_num[i])
    return product_even % sum_odd == 0

print(is_divisible(123456))

Output: True

This code defines the function is_divisible(), which converts the number to a string for easy index-based access to individual digits. It then iterates through the digits, summing those at odd indices (0-based) and multiplying those at even indices, before testing divisibility.

Method 2: List Comprehension with Enumerate

In this method, we use Python’s powerful list comprehensions combined with the enumerate function to concisely create lists of even and odd indexed digits, and then perform the product and sum operations.

Here’s an example:

def is_divisible(number):
    str_num = str(number)
    odd_digits = [int(digit) for idx, digit in enumerate(str_num) if idx % 2 == 0]
    even_digits = [int(digit) for idx, digit in enumerate(str_num) if idx % 2 != 0]
    return prod(even_digits) % sum(odd_digits) == 0

from math import prod
print(is_divisible(123456))

Output: True

The function is_divisible() separates the even and odd indexed digits using list comprehensions and the enumerate() function, calculates their product and sum using Python’s built-in functions prod() and sum(), and then checks for divisibility.

Method 3: Functional Approach with Reduce

Utilizing the functional programming concept, we can use the ‘reduce’ function from ‘functools’ module along with a lambda function to compute the product of even digits, making the code more concise and more ‘Pythonic’.

Here’s an example:

from functools import reduce

def is_divisible(number):
    str_num = str(number)
    even_product = reduce(lambda x, y: x * y, [int(str_num[i]) for i in range(1, len(str_num), 2)], 1)
    odd_sum = sum(int(str_num[i]) for i in range(0, len(str_num), 2))
    return even_product % odd_sum == 0

print(is_divisible(123456))

Output: True

The function is_divisible() employs the reduce() function to multiply the even-indexed digits and a generator expression within the sum() function for the odd-indexed digits before checking for divisibility. This approach embraces the functional programming paradigm.

Method 4: Using Map and Filter

This method combines map and filter functions to selectively process the even and odd indexed digits and leverages these higher-order functions to improve code expressiveness and readability.

Here’s an example:

def is_divisible(number):
    str_num = str(number)
    even_digits = map(int, filter(lambda i: i[0] % 2, enumerate(str_num)))
    odd_digits = map(int, filter(lambda i: i[0] % 2 == 0, enumerate(str_num)))
    return prod(even_digits) % sum(odd_digits) == 0

from math import prod
print(is_divisible(123456))

Output: True

By filtering the enumerated number string with lambdas checking the index, is_divisible() separates even and odd indexed digits and then maps them to their integer forms. The product of even digits and sum of odd digits are then computed using prod() and sum(), finishing with the divisibility check.

Bonus One-Liner Method 5: Compact Expression

This one-liner method is for Python enthusiasts who admire brevity. It cleverly uses slicing and reduces to compute the desired result in a single, albeit dense, line of code.

Here’s an example:

from functools import reduce
from operator import mul

is_divisible = lambda n: reduce(mul, map(int, str(n)[1::2]), 1) % sum(map(int, str(n)[::2])) == 0
print(is_divisible(123456))

Output: True

The anonymous function is_divisible represented as a lambda expression carries out the task by applying reduce with multiplication on sliced string for even indexed digits and sum function on sliced string for odd indexed digits, ultimately checking the divisibility condition in a succinct manner.

Summary/Discussion

  • Method 1: Iterative Approach using Loops. Easily understandable. Potential verbosity with explicit loops.
  • Method 2: List Comprehension with Enumerate. Elegant and Pythonic. Requires understanding of list comprehensions and enumerate().
  • Method 3: Functional Approach with Reduce. Embraces functional programming. Can be less intuitive for programmers unfamiliar with functional concepts.
  • Method 4: Using Map and Filter. Expressive use of higher-order functions. Slightly complex for those not comfortable with map/filter.
  • Method 5: Compact Expression. Extremely concise. May sacrifice readability for brevity, not suitable for novices.