0

我试图了解如何编写将输出数字的所有除数的代码。我最感兴趣的方法从一个返回字典的函数开始,其中键是主要除数,值是可除数。我已经像这样编写了这个函数:

def div_pair(num):
    divPair = {}
    for prime in prime_gen():
        primeDegree = 0
        while num % prime == 0:
            num = int(num / prime)
            primeDegree += 1
        if primeDegree > 0:
            divPair[prime] = primeDegree
        if num == 1:
            return divPair

例如,数字 84,000 输出字典

{2: 5, 3: 1, 5: 3, 7: 1}

我想从这里做的是生成由不同数字 divPair 返回的任何给定值的幂集(?),然后将这些幂集乘以它们匹配的素数。这是一个示例,它使用我试图用来生成 powerset 的那种代码:

from itertools import product
list(product(range(5+1), range(1+1), range(3+1), range(1+1)))

输出这个:

[(0, 0, 0, 0),
 (0, 0, 0, 1),
 (0, 0, 1, 0),
 (0, 0, 1, 1),
 (0, 0, 2, 0),
 (0, 0, 2, 1),
 (0, 0, 3, 0),
 (0, 0, 3, 1),
 (0, 1, 0, 0),
 (0, 1, 0, 1),
 (0, 1, 1, 0),
 (0, 1, 1, 1),
 (0, 1, 2, 0),
 (0, 1, 2, 1),
 (0, 1, 3, 0),
 (0, 1, 3, 1),
 (1, 0, 0, 0),
 (1, 0, 0, 1),
 (1, 0, 1, 0),
 (1, 0, 1, 1),
 (1, 0, 2, 0),
 (1, 0, 2, 1),
 (1, 0, 3, 0),
 (1, 0, 3, 1),
 (1, 1, 0, 0),
 (1, 1, 0, 1),
 (1, 1, 1, 0),
 (1, 1, 1, 1),
 (1, 1, 2, 0),
 (1, 1, 2, 1),
 (1, 1, 3, 0),
 (1, 1, 3, 1),
 (2, 0, 0, 0),
 (2, 0, 0, 1),
 (2, 0, 1, 0),
 (2, 0, 1, 1),
 (2, 0, 2, 0),
 (2, 0, 2, 1),
 (2, 0, 3, 0),
 (2, 0, 3, 1),
 (2, 1, 0, 0),
 (2, 1, 0, 1),
 (2, 1, 1, 0),
 (2, 1, 1, 1),
 (2, 1, 2, 0),
 (2, 1, 2, 1),
 (2, 1, 3, 0),
 (2, 1, 3, 1),
 (3, 0, 0, 0),
 (3, 0, 0, 1),
 (3, 0, 1, 0),
 (3, 0, 1, 1),
 (3, 0, 2, 0),
 (3, 0, 2, 1),
 (3, 0, 3, 0),
 (3, 0, 3, 1),
 (3, 1, 0, 0),
 (3, 1, 0, 1),
 (3, 1, 1, 0),
 (3, 1, 1, 1),
 (3, 1, 2, 0),
 (3, 1, 2, 1),
 (3, 1, 3, 0),
 (3, 1, 3, 1),
 (4, 0, 0, 0),
 (4, 0, 0, 1),
 (4, 0, 1, 0),
 (4, 0, 1, 1),
 (4, 0, 2, 0),
 (4, 0, 2, 1),
 (4, 0, 3, 0),
 (4, 0, 3, 1),
 (4, 1, 0, 0),
 (4, 1, 0, 1),
 (4, 1, 1, 0),
 (4, 1, 1, 1),
 (4, 1, 2, 0),
 (4, 1, 2, 1),
 (4, 1, 3, 0),
 (4, 1, 3, 1),
 (5, 0, 0, 0),
 (5, 0, 0, 1),
 (5, 0, 1, 0),
 (5, 0, 1, 1),
 (5, 0, 2, 0),
 (5, 0, 2, 1),
 (5, 0, 3, 0),
 (5, 0, 3, 1),
 (5, 1, 0, 0),
 (5, 1, 0, 1),
 (5, 1, 1, 0),
 (5, 1, 1, 1),
 (5, 1, 2, 0),
 (5, 1, 2, 1),
 (5, 1, 3, 0),
 (5, 1, 3, 1)]

这真的是我想要的输出。我只需要修改代码以某种方式接受 divPair.values() 。所以我写这个:

from itertools import product
divPair = div_pair(84000)
list(product(range(i+1) for i in divPair.values()))

在我看来它应该是正确的,但它输出了这个混乱:

[(range(0, 6),), (range(0, 2),), (range(0, 4),), (range(0, 2),)]

我不知道如何解决它。这里有一篇文章为我正在尝试做的事情提供了极好的解决方案。我只是想用我所知道的向他们努力。

4

1 回答 1

2

product返回其参数的乘积,并且您已将其传递给它一个,即 (range(i+1) for i in divPair.values())生成器。生成器产生了一个range对象列表。就像这样做:

>>> list(product(['range', 'range', 'range']))
[('range',), ('range',), ('range',)]

 

您必须将范围作为单独的参数传递。

做这个:

list(product(*[range(i+1) for i in divPair.values()]))

(或这个)

list(product(*(range(i+1) for i in divPair.values())))
于 2013-03-11T20:14:10.383 回答