Python recursive program to prime factorize a number

前端 未结 5 640
庸人自扰
庸人自扰 2021-01-22 14:07

I wrote the following program to prime factorize a number:

import math
def prime_factorize(x,li=[]):
    until = int(math.sqrt(x))+1
    for i in xrange(2,until)         


        
5条回答
  •  抹茶落季
    2021-01-22 14:41

    Your prime_factorize function doesn't have a return statement in the recursive case -- you want to invoke "return prime_factorize(x/i,li)" on its last line. Try it with a prime number (so the recursive call isn't needed) to see that it works in that case.

    Also you probably want to make the signature something like:

    def prime_factorize(x,li=None):
        if li is None: li = []
    

    otherwise you get wrong results when calling it two or more times:

    >>> prime_factorize(10)
    [2, 5]
    >>> prime_factorize(4)
    [2, 5, 2, 2]
    >>> prime_factorize(19)
    [2, 5, 2, 2, 19]
    

提交回复
热议问题