Python的递归程序向总理比化了一些 [英] Python recursive program to prime factorize a number

查看:119
本文介绍了Python的递归程序向总理比化了一些的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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]

这篇关于Python的递归程序向总理比化了一些的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆