Python factorization

前端 未结 5 1390
清歌不尽
清歌不尽 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:24

    Well, not only you have 3 loops, but this approach won't work if you have more than 3 factors :)

    One possible way:

    def genfactors(fdict):    
        factors = set([1])
    
        for factor, count in fdict.iteritems():
            for ignore in range(count):
                factors.update([n*factor for n in factors])
                # that line could also be:
                # factors.update(map(lambda e: e*factor, factors))
    
        return factors
    
    factors = {2:3, 3:2, 5:1}
    
    for factor in genfactors(factors):
        print factor
    

    Also, you can avoid duplicating some work in the inner loop: if your working set is (1,3), and want to apply to 2^3 factors, we were doing:

    • (1,3) U (1,3)*2 = (1,2,3,6)
    • (1,2,3,6) U (1,2,3,6)*2 = (1,2,3,4,6,12)
    • (1,2,3,4,6,12) U (1,2,3,4,6,12)*2 = (1,2,3,4,6,8,12,24)

    See how many duplicates we have in the second sets?

    But we can do instead:

    • (1,3) + (1,3)*2 = (1,2,3,6)
    • (1,2,3,6) + ((1,3)*2)*2 = (1,2,3,4,6,12)
    • (1,2,3,4,6,12) + (((1,3)*2)*2)*2 = (1,2,3,4,6,8,12,24)

    The solution looks even nicer without the sets:

    def genfactors(fdict):
        factors = [1]
    
        for factor, count in fdict.iteritems():
            newfactors = factors
            for ignore in range(count):
                newfactors = map(lambda e: e*factor, newfactors)
                factors += newfactors
    
        return factors
    

提交回复
热议问题