views:

201

answers:

2

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!

+14  A: 

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.

Mark Dickinson
+999 Very nice!
Hamish Grubijan
+2  A: 

Here's my solution (not as elegant as Mark's, but it still works):

from itertools import permutations

for perm in permutations('123456789'):
    isgood = 1
    for i in xrange(9):
        if(int(''.join(perm[:9-i])) % (9-i)):
            isgood = 0
            break
    if isgood:
        print ''.join(perm)
Justin Peel
I want to time it, but I see Python 2.x code, and I do not want to compare apples and oranges.
Hamish Grubijan
Oh yeah, it did say Python 3.x, oops
Justin Peel
Mine isn't anywhere near as optimized as it could be either.. but why bother on something like this?
Justin Peel
Ok, my goal is to keep a coworker of mine on his toes. He is so in love with everything Microsoft, that I want to show him other ways to live. Do not worry about optimization if you do not feel like it. Thanks for contributing.
Hamish Grubijan