如何求一个给定素因子分解的数的因子?

2024-03-28 10:02:27 发布

您现在位置:Python中文网/ 问答频道 /正文

如果给我一个[2, 2, 3, 5, 5]形式的数的素因子分解,我怎么能找到[1, 2, 3, 4, 5, 6, 10, 12, 15, 20, 25, 30, 50, 60, 75, 100, 150, 300]形式的所有因子

我曾尝试通过迭代循环来实现这一点,但据我所知,这并不是通过单击一种方法来获得数字,结果是两个以上的数字相乘

def find_factors(pfacts):
    pfacts = [1] + pfacts
    temp = []
    for i in pfacts:
        for j in pfacts[i+1:]:
            if i * j not in temp:
                temp.append(i * j)
    return [1] + temp

我知道这不是正确的方法,因为它只能找到一小部分的因素

[1, 2, 3, 5, 6, 10, 15]

Tags: 方法inforreturnifdefnot数字
3条回答

一种方法是将itertools.productnumpy.prodnumpy.power一起使用:

import numpy as np
from itertools import product

f = [2, 2, 3, 5, 5]
uniq_f = np.unique(f)
counts = np.array(list(product(*(range(f.count(i) + 1) for i in uniq_f))))
sorted(np.prod(np.power(uniq_f, counts), 1))

输出:

[1, 2, 3, 4, 5, 6, 10, 12, 15, 20, 25, 30, 50, 60, 75, 100, 150, 300]

把所有的组合相乘,然后加到一个集合中。你知道吗

import itertools

def multiplyList(myList):
    # Multiply elements one by one
    result = 1
    for x in myList:
        result = result * x
    return result

factors=set()

stuff = [2, 2, 3, 5, 5]
for L in range(0, len(stuff)+1):
    for subset in itertools.combinations(stuff, L):
        factors.add(multiplyList(subset))

factors=list(sorted(factors))

print(factors)

其工作原理如下:

[1, 2, 3, 4, 5, 6, 10, 12, 15, 20, 25, 30, 50, 60, 75, 100, 150, 300]

您可以使用itertools.combinations(这将提供重复项)和set来过滤重复项:

from itertools import combinations
from functools import reduce
from operator import mul

factors = [2, 2, 3, 5, 5]

set(reduce(mul, combination) for i in range (1, len(factors) + 1) for combination in combinations(factors, i))

输出:

{2, 3, 4, 5, 6, 10, 12, 15, 20, 25, 30, 50, 60, 75, 100, 150, 300}

相关问题 更多 >