當前位置: 首頁>>代碼示例>>Python>>正文


Python Permutation.get_all_permutations方法代碼示例

本文整理匯總了Python中permutation.Permutation.get_all_permutations方法的典型用法代碼示例。如果您正苦於以下問題:Python Permutation.get_all_permutations方法的具體用法?Python Permutation.get_all_permutations怎麽用?Python Permutation.get_all_permutations使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在permutation.Permutation的用法示例。


在下文中一共展示了Permutation.get_all_permutations方法的1個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: __init__

# 需要導入模塊: from permutation import Permutation [as 別名]
# 或者: from permutation.Permutation import get_all_permutations [as 別名]
class Divisor:
    def __init__(self,):
        self.__mod_prime = Prime()
        self.__mod_permutation = Permutation()

    def get_count_of_divisors(self, n):
        """
        >>> D = Divisor()
        >>> D.get_count_of_divisors(2)
        2

        >>> D.get_count_of_divisors(100)
        9

        >>> D.get_count_of_divisors(-1)
        Traceback (most recent call last):
        ValueError: input has to be a positive int or long: -1
        """
        if isinstance(n, (int, long)) == False or n <= 0:
            raise ValueError("input has to be a positive int or long: %s" %n)
        if n == 1:
            return 1
        # n = (a ** p) * (b ** q) * (c ** r) のとき、
        # n の約數は (p + 1) * (q + 1) * (r + 1) で求められる
        factors = self.__mod_prime.get_prime_factors(n)
        powers = [v + 1 for v in factors.values()] # [p+1, q+1, r+1, ...]
        return reduce(lambda x, y: x * y, powers)

    def get_proper_divisors(self, n, n_large = 2000):
        """
        >>> D = Divisor()
        >>> D.get_proper_divisors(28)
        [1, 2, 4, 7, 14]

        >>> D.get_proper_divisors(200)
        [1, 2, 4, 5, 8, 10, 20, 25, 40, 50, 100]
        """
        if n >= n_large:
            return self._get_pds1(n)
        else:
            return self._get_pds2(n)

    def _get_pds1(self, n):
        prime_factors = self.__mod_prime.get_prime_factors(n)

        # prime_all_powers
        prime_all_powers = {}
        # for n=600 primes = [2, 3, 5]
        for prime,power in prime_factors.items(): # for n=200 prime=2,5
            prime_all_powers[prime] = [prime * pw for pw in range(power)]
        # for n=600 prime_all_powers = {2:[1,2,4,8], 3:[1,3], 5:[1,5,25]}

        res = []
        for pair in self.__mod_permutation.get_all_permutations(prime_all_powers.values()):
            # pairs: [1,1,1], [1,1,5], [1,1,25], [1,3,1], [1,3,5], [1,3,25], .... [8,3,25]
            res.append( reduce(lambda x,y: int(x)*int(y), pair) )
        return res

    def _get_pds2(self, n):
        pds = []
        for i in range(1, int(n / 2) + 1):
            if n % i == 0:
                pds.append( i )
        return pds
開發者ID:m-a-t-h,項目名稱:peppy,代碼行數:66,代碼來源:divisor.py


注:本文中的permutation.Permutation.get_all_permutations方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。