5 Best Ways to Check if All Digits of a Number Divide It in Python

Rate this post

πŸ’‘ Problem Formulation: Given an integer, how do we determine if every non-zero digit within the number divides the number itself? For example, considering the number 128, the digits 1, 2, and 8 all divide 128 evenly, thereby making it true for this problem. The desired output in this case would be a boolean value, True or False, indicating the divisibility of the number by each of its digits.

Method 1: Iteration and Modulo Operation

The first method involves iterating over each digit of the number and performing a modulo operation to check if the number is divisible by that digit. It’s a straightforward approach where you convert the integer to a string, iterate through the string, convert each character back to an integer, and then check divisibility.

Here’s an example:

def check_divisibility(n):
    num_str = str(n)
    for digit in num_str:
        if digit == '0' or n % int(digit) != 0:
            return False
    return True

# Example:
print(check_divisibility(128))

Output: True

The function check_divisibility above takes an integer n, converts it to a string to iterate over its digits, checks for zeros, and evaluates whether each digit divides the number. If all digits divide it, the function returns True.

Method 2: Using List Comprehension

List comprehension in Python allows us to create lists in a single line of code by applying an expression to each element in an iterable. The same logic as Method 1 can be applied using a more compact list comprehension syntax, which can make the code shorter and often more readable.

Here’s an example:

def check_divisibility(n):
    return all(n % int(digit) == 0 for digit in str(n) if digit != '0')

# Example:
print(check_divisibility(128))

Output: True

This check_divisibility function is a condensed version that uses list comprehension and the built-in all() function, which checks for divisibility only when the digit is not zero, and returns True if all conditions are met.

Method 3: Using Functional Programming

Functional programming concepts like map and filter can be utilized in Python to perform operations in a declarative manner. In this method, we use filter to remove zeroes and map to apply the divisibility test across all digits.

Here’s an example:

def check_divisibility(n):
    digits = map(int, filter(lambda x: x != '0', str(n)))
    return all(n % digit == 0 for digit in digits)

# Example:
print(check_divisibility(128))

Output: True

This version uses filter to ignore ‘0’ characters and the map function to apply the divisibility check. The combination of these functional programming tools makes for clean and expressive code.

Method 4: Using Division and Mod](ulo without String Conversion

An alternative approach involves manipulating the number arithmetically without converting it to a string. This method uses division and the modulo operator to extract each digit and check its divisibility, thus avoiding the overhead of string manipulation.

Here’s an example:

def check_divisibility(n):
    original = n
    while n > 0:
        digit = n % 10
        if digit == 0 or original % digit != 0:
            return False
        n //= 10
    return True

# Example:
print(check_divisibility(128))

Output: True

Here, n % 10 retrieves the last digit, while n //= 10 removes the last digit from consideration in the next iteration. This method is efficient as it doesn’t rely on string conversions, making it faster for large numbers.

Bonus One-Liner Method 5: Functional One-Liner with Execption Handling

In Python, conciseness can often be achieved with one-liners. This method combines a try-except block with a one-liner, providing a neat way to handle the edge case of division by zero within the list comprehension.

Here’s an example:

def check_divisibility(n):
    try:
        return all(n % int(d) == 0 for d in str(n) if d > '0')
    except ZeroDivisionError:
        return False

# Example:
print(check_divisibility(128))

Output: True

The function above uses exception handling to return False if a zero division occurs, otherwise it checks the divisibility of digits using a one-liner list comprehension. It’s elegant and concise, but the try-except block may introduce a slight overhead.

Summary/Discussion

  • Method 1: Iterative with Modulo. Easy to understand and implement. May not be the most Pythonic or efficient with large numbers.
  • Method 2: List Comprehension. More concise than Method 1, and Pythonic. Still, involves string conversion which can be a bit slower.
  • Method 3: Functional Programming. Leveraging map and filter for a declarative approach. It may be less intuitive for those unfamiliar with functional programming concepts.
  • Method 4: Arithmetic without String Conversion. Avoids the cost of converting a number to a string and back. Can be more efficient, especially with larger numbers. However, the approach is slightly more complex.
  • Bonus Method 5: Functional One-Liner with Exception Handling. Compact and Pythonic. The exception handling adds robustness but may introduce minor performance overhead.