我试图了解如何编写将输出数字的所有除数的代码。我最感兴趣的方法从一个返回字典的函数开始,其中键是主要除数,值是可除数。我已经像这样编写了这个函数:
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),)]
我不知道如何解决它。这里有一篇文章为我正在尝试做的事情提供了极好的解决方案。我只是想用我所知道的向他们努力。