帮我完成Python 3.x的自我挑战

时间:2010-04-15 22:45:29

标签: python python-3.x puzzle combinatorics

这不是作业。

我看到了this article praising Linq library and how great it is做组合术的事情,我心想:Python可以用更易读的方式做到。

用Python轻拍半小时后,我失败了。请在我离开的地方完成。另外,请以最恐怖和最有效的方式来做。

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)

谢谢!

4 个答案:

答案 0 :(得分:24)

这是一个简短的解决方案,使用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)

我故意省略了1和9的可分性检查,因为它们总会得到满足。

答案 1 :(得分:3)

这是我的解决方案。我喜欢自下而上的所有事情;-)。在我的机器上,它比Marks:

快580倍(3.1毫秒对1.8秒)
def generate(digits, remaining=set('123456789').difference):
    return (n + m
        for n in generate(digits - 1)
            for m in remaining(n)
                if int(n + m) % digits == 0) if digits > 0 else ['']

for each in generate(9):
    print(int(each))

编辑:此外,这是有效的,速度是原来的两倍(1.6毫秒):

from functools import reduce

def generate():
    def digits(x):
        while x:
            x, y = divmod(x, 10)
            yield y
    remaining = set(range(1, 10)).difference
    def gen(numbers, decimal_place):
        for n in numbers:
            for m in remaining(digits(n)):
                number = 10 * n + m
                if number % decimal_place == 0:
                    yield number
    return reduce(gen, range(2, 10), remaining())

for each in generate():
    print(int(each))

答案 2 :(得分:2)

这是我的解决方案(不像Mark那样优雅,但它仍然有效):

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)

答案 3 :(得分:1)

这是我的解决方案,它与Marks非常相似,但运行速度快了两倍

from itertools import permutations

def is_solution(seq):
    if seq[-1]=='9':
        for i in range(8,1,-1):
            n = -(9-i)
            if eval(seq[:n]+'%'+str(i))==0:
                continue
            else:return False
        return True
    else:return False
for p in permutations('123456789'):
    seq = ''.join(p)
    if is_solution(seq):
        print(seq)