Python factorization

前端 未结 5 1392
清歌不尽
清歌不尽 2020-12-16 19:03

I\'d just like to know the best way of listing all integer factors of a number, given a dictionary of its prime factors and their exponents.
For example if we have {2:3

5条回答
  •  我在风中等你
    2020-12-16 19:37

    Using itertools.product from Python 2.6:

    #!/usr/bin/env python
    import itertools, operator
    
    def all_factors(prime_dict):
        series = [[p**e for e in range(maxe+1)] for p, maxe in prime_dict.items()]
        for multipliers in itertools.product(*series):
            yield reduce(operator.mul, multipliers)
    

    Example:

    print sorted(all_factors({2:3, 3:2, 5:1}))
    

    Output:

    [1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, 18, 20, 24, 30, 36, 40, 45, 60,
     72, 90, 120, 180, 360]
    

提交回复
热议问题