Python的递归程序向总理比化了一些递归、总理、程序、Python

由网友(陪伴是最长情的告白)分享简介:我写了下面的程序,以质比化一些:I wrote the following program to prime factorize a number:import mathdef prime_factorize(x,li=[]):until = int(math.sqrt(x))+1for i in xrange(...

我写了下面的程序,以质比化一些:

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):
    	if not x%i:
    	    li.append(i)
    	    break
    else:                      #This else belongs to for
    	li.append(x)
    	print li               #First print statement; This is what is returned
    	return li
    prime_factorize(x/i,li)

if __name__=='__main__':
    print prime_factorize(300)   #Second print statement, WTF. why is this None

以下是我得到的输出:

Following is the output I get:

 [2, 2, 3, 5, 5]
 None

Altho,返回的值将被打印正常,后返回值似乎没有印刷,所有的时间。我在想什么?

Altho', the returned value is printed properly, the after returned value seems to be printing none, all the time. What am I missing?

另外,我怎么能改善方案(继续使用递归)

Also, how can I improve the program (continuing to use the recursion)

推荐答案

您prime_factorize功能没有在递归情况下return语句 - 你想要调用返回prime_factorize(X / I,LI)在其最后一行。与一个素数(所以递归调用不需要)尝试它,看,它的作品在这种情况下。

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]
阅读全文

相关推荐

最新文章