Check if any permutation of a number is divisible by 3 and is Palindromic in Python



Divisibility by 3

The given task is to determine whether the permutation of the digits of the given number can form a new number that satisfies two conditions: it must be divisible by 3 and also be a palindromic number.

A number is said to be palindromic if the reversal of a number is the same as the original, such as 121 or 1331, and a number is said to be divisible by 3 if the sum of its digits is divisible by 3. For example, let's look at the following scenarios: 

Scenario 1

Input: 121
Output: False
Explanation:
For the given input the permutations are : 121, 112, 211 among these, only 121 is palindrome. The sum of its digits (1+2+1=4) which is not divisible by 3. so the result is false.

Scenario 2

Input: 303
Output: True
Explanation:
For the given input the permutations are 033, 303, 330, etc. Among these 
Among these 303 is palindrome. The sum of its digits 3+0+3=9 which is divisible by 3. Hence the result is true.

Let's dive into the example to understand more about checking if any permutation of a number is divisible by 3 and is palindromic.

Example: Divisibility by 3 Using Python

In the following example, we are going to check whether the given input is palindromic and is divisible by 3 or not.

from itertools import permutations
def x(num_str):
   return sum(int(d) for d in num_str) % 3 == 0
def y(num_str):
   return num_str == num_str[::-1]
def demo(n):
   a = str(n)
   b = set()
   for p in permutations(a):
      if p[0] == '0': 
         continue
      c = ''.join(p)
      if c in b:
         continue
      b.add(c)
      if y(c) and x(c):
         return True
   return False
print(demo(121))
print(demo(303))

Following is the output of the above program:

False
True
Updated on: 2025-08-07T18:49:53+05:30

193 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements