这是我解决项目欧拉问题的一部分.无论如何我已经以更好的方式解决了这个问题,但这仍然让我很烦,因为函数似乎工作正常 – 它似乎知道我想要返回的变量的值.
def next_prime(prevIoUs): if prevIoUs % 2 == 0: candIDate = prevIoUs + 1 else: candIDate = prevIoUs + 2 print "trying",candIDate prime = True for div in range(2,candIDate//2,1): if candIDate % div == 0: prime = False print candIDate,"is not prime - divisible by",div next_prime(candIDate) break if prime is True: print candIDate,"is prime" #return candIDatelast = 896576print "After",last,",the next prime is..."next_prime(last)
这给出了:
After 896576,the next prime is...trying 896577896577 is not prime - divisible by 3trying 896579896579 is not prime - divisible by 701trying 896581896581 is not prime - divisible by 7trying 896583896583 is not prime - divisible by 3trying 896585896585 is not prime - divisible by 5trying 896587896587 is prime
但是如果我取消注释return语句,它只返回一个值,如果第一次尝试是素数,否则它返回None.
解决方法 当找不到素数时,您忘记返回值:for div in range(2,1): if candIDate % div == 0: prime = False print candIDate,div return next_prime(candIDate)
这里递归并不适合.它比简单的迭代方法更优雅.此外,如果您遇到两个连续素数之间存在大量非素数的区域,您可能会溢出堆栈.
总结以上是内存溢出为你收集整理的Python函数在递归后返回None全部内容,希望文章能够帮你解决Python函数在递归后返回None所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)