帮我完成这个 Python 3.x 自我挑战

发布于 2024-08-29 06:04:11 字数 810 浏览 11 评论 0原文

这不是家庭作业。

我看到这篇文章赞扬了 Linq 库以及它的伟大组合学的东西,我心想:Python 可以以一种更易读的方式做到这一点。

经过半个小时的Python尝试,我失败了。请从我停下来的地方继续。另外,请尽可能以最 Pythonic 和最有效的方式进行操作。

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)

谢谢!

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!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

ゃ懵逼小萝莉 2024-09-05 06:04:11

这是一个简短的解决方案,使用 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 的整除性,因为它们总是令人满意的。

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.

乖乖公主 2024-09-05 06:04:11

这是我的解决方案。我喜欢自下而上的所有事情;-)。在我的机器上,它的运行速度比 Marks 快大约 580 倍(3.1 毫秒 vs. 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))

Here's my solution. I like all things bottom-up ;-). On my machine it runs about 580 times faster (3.1 msecs vs. 1.8 secs) than Marks:

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))

EDIT: Also, this works, and twice as fast (1.6 msecs):

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))
狠疯拽 2024-09-05 06:04:11

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

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)

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)
有木有妳兜一样 2024-09-05 06:04:11

这是我的解决方案,它与 Marks 非常相似,但运行速度大约是 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)

this is my solution, it is very similar to Marks, but it runs about twice as fast

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)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文