我无法弄清楚为什么这个python函数在递归调用自身时会返回None。
这是我解决项目欧拉问题的一部分。我无论如何都以更好的方式解决了这个问题,但这仍然让我感到烦恼,因为函数似乎工作正常 - 它似乎知道我想要返回的变量的值。
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 candidate
last = 896576
print "After", last, ", the next prime is..."
next_prime(last)
这给出了:
After 896576 , the next prime is...
trying 896577
896577 is not prime - divisible by 3
trying 896579
896579 is not prime - divisible by 701
trying 896581
896581 is not prime - divisible by 7
trying 896583
896583 is not prime - divisible by 3
trying 896585
896585 is not prime - divisible by 5
trying 896587
896587 is prime
但是如果我取消注释return语句,它只返回一个值,如果第一次尝试是素数,否则返回None。
答案 0 :(得分:6)
如果找不到素数,你忘了返回一个值:
for div in range(2,candidate//2,1):
if candidate % div == 0:
prime = False
print candidate, "is not prime - divisible by", div
return next_prime(candidate)
虽然递归并不适合这里。它比简单的迭代方法更优雅。此外,如果您遇到两个连续素数之间存在大量非素数的区域,您可能会溢出堆栈。
答案 1 :(得分:1)
正如其他人所说,这不是递归的真正地方。以下是使用迭代的示例。我还定义了另一个测试整数的素数的函数 - 我认为这会使代码更简单。
def is_prime(n):
"""Return True if n is prime."""
for i in xrange(2, n//2):
if n%i == 0:
return False
return True
def next_prime(n):
"""Returns the next prime number after n."""
if n % 2 == 0:
candidate = n + 1
else:
candidate = n + 2
while not is_prime(candidate):
candidate += 2
return candidate
if __name__ == '__main__':
n = 896576
print next_prime(n)
答案 2 :(得分:0)
请注意,您正在对next_prime函数进行递归调用,但不会从调用函数返回它的值。
替换行:
print candidate, "is not prime - divisible by", div
next_prime(candidate)
与
print candidate, "is not prime - divisible by", div
return next_prime(candidate)