I'm trying to solve this problem from codewars.
Problem
Given a certain number, how many multiples of three could you obtain with its digits? Suppose that you have the number
362
. The numbers that can be generated from it are:3, 6, 2, 36, 63, 62, 26, 32, 23, 236, 263, 326, 362, 623, 632
and among those3, 6, 36, 63
are divisible by3
.We need a function that can receive a number ann may output in the following order:
the amount of multiples(without
0
)the maximum multiple
My solution
I have found all possible permutations of the digits of the given number and checked if the number is divisible by 3
. Here is my code -
from itertools import permutations as perm
from functools import reduce
def to_int(digs): # takes a list of digits of an integer and returns the number
n = reduce(lambda total, d: 10 * total + d, digs, 0)
return n
def find_mult_3(num):
digs = list(map(int, str(num)))
perms = [] # stores all possible permutations with the digits of num
for i in range(1, len(digs)+1):
perms.extend(list(p) for p in set(perm(digs, i)))
count, mx = 0, 0
seen = set() # to keep track of divisors already seen
if 0 in perms:
perms.remove(0)
for p in perms:
n = to_int(p)
if n % 3 == 0 and n not in seen:
if mx < n:
mx = n
count += 1
seen.add(n)
return [count, mx]
But getting TLE
, is there any way to make this program faster or any other clever way to solve this problem? Please ask if there is any need for clarification in any part of the code.
to_int()
function. \$\endgroup\$