from itertools import combinations def swap(l, i, j): a, b = l[i], l[j] l[j] = a l[i] = b def to_int(l): # Coverts list of digits to integer. n = 0 for i, x in enumerate(reversed(l)): n += x * 10**i return n def next_greatest(l): # Finds the next greatest number with the same set of digits. # First, the first index (from the right) where Left > Right digit. for i in range(len(l)-1, -1, -1): if l[i] < l[i-1]: break if i == 0: return 0 # No digits, found, smallest possible. # Find the largest number to the right of that index, including, # and swap. Then, sort the right descending. comp, largest = l[i-1], i for j in range(i, len(l)): if l[j] < comp and l[j] > l[largest]: largest = j swap(l, i-1, largest) l = l[:i] + sorted(l[i:], reverse=True) def solution(l): l = sorted(l, reverse=True) found = False for i in range(len(l), 0, -1): # Get all combinations when removing digits. c = list(combinations(l, i)) for m in c: m = list(m) while True: num = to_int(m) if num % 3 == 0: return num if not next_greatest(m): break return 0