Categories

# Help me finish this Python 3.x self-challenge

This is not homework.

I saw this article praising Linq library and how great it is for doing combinatorics stuff, and I thought to myself: Python can do it in a more readable fashion.

After half hour of dabbing with Python I failed. Please finish where I left off. Also, do it in the most Pythonic and efficient way possible please.

``from itertools import permutations from operator import mul from functools import reduce glob_lst = [] def divisible(n): return (sum(j*10^i for i,j in enumerate(reversed(glob_lst))) % n == 0) oneToNine = list(range(1, 10)) twoToNine = oneToNine[1:] for perm in permutations(oneToNine, 9):     for n in twoToNine:         glob_lst = perm[1:n]         #print(glob_lst)         if not divisible(n):             continue     else:         # Is invoked if the loop succeeds         # So, we found the number         print(perm) ``

Thanks!

Here’s a short solution, using itertools.permutations:

``from itertools import permutations def is_solution(seq):     return all(int(seq[:i]) % i == 0 for i in range(2, 9)) for p in permutations('123456789'):     seq = ''.join(p)     if is_solution(seq):         print(seq) ``

I’ve deliberately omitted the divisibility checks by 1 and by 9, since they’ll always be satisfied.