Python - 将数字的因子按排序顺序放入数组中

时间:2016-02-27 17:29:24

标签: python algorithm sorting factors

我写过这个算法,找到给定数字的所有因子并将它们放入一个列表中:

def find_all_factors(n):
    factors = []
    for i in range(1, floor(sqrt(n))+1):
        if n % i == 0:
            factors.append(i)
            cofactor = n // i
            if i != cofactor: factors.append(cofactor)
    return factors

在列表中,cofactors将放在彼此旁边,但我希望它们以排序的顺序出现。上述算法的输出示例:对于n = 36,它输出[1, 36, 2, 18, 3, 12, 4, 9, 6]。我这样做是为了练习,我想知道按顺序排序的最有效方法是什么?有什么想法吗?

您可以在下面看到我的解决方案之一。它有效,但我认为它不是最佳的。

def find_all_factors(n):
    lower_factors = []
    higher_factors = []
    for i in range(1, floor(sqrt(n))+1):
        if n % i == 0:
            lower_factors.append(i)
            cofactor = n // i
            if i != cofactor: higher_factors.append(cofactor)
    return lower_factors + [higher_factors[-i] for i in range(1, len(higher_factors)+1)]  #Reverses higher_factors.

3 个答案:

答案 0 :(得分:1)

只需返回已排序的列表:

return sorted(factors)

如果您不喜欢使用sorted函数,只需将循环范围更改为(1,n + 1):

def find_all_factors(n):
    factors = []
    for i in range(1, n+1):
        if n % i == 0:
            factors.append(i)
    return factors

find_all_factors(12) # [1, 2, 3, 4, 6, 12]

另一种方法是使用bisect(最有效的方法):

import bisect
def find_all_factors(n):
    factors = []
    for i in range(1, math.floor(math.sqrt(n))+1):
        if n % i == 0:
            bisect.insort(factors,i)
            cofactor = n // i
            if i != cofactor: bisect.insort(factors, cofactor)
    return factors

find_all_factors(12) # [1, 2, 3, 4, 6, 12]

在此模块中插入O(n),但搜索为O(log(n))

答案 1 :(得分:1)

您缺少的一件事是在列表上操作更简单,更容易。有一个内置的Python用于反转序列:reversed.

所以你可以这样做:

return lower_factors + list(reversed(higher_factors))

答案 2 :(得分:0)

from math import floor, sqrt


def find_all_factors(n):
    factors = []
    for i in xrange(1, int(floor(sqrt(n)))+1):
        quotient, remainder = divmod(n, i)
        if remainder == 0:
            factors.append(i)
            if quotient not in factors:
                factors.append(quotient)
    return sorted(factors)

print find_all_factors(36)

输出:[1, 2, 3, 4, 6, 9, 12, 18, 36]