Python 函数在递归后返回 None [英] Python function returning None after recursion

查看:38
本文介绍了Python 函数在递归后返回 None的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不明白为什么这个 python 函数在递归调用自己时返回 None.

I can't figure out why this python function returns None if it calls itself recursively.

这是我解决 Project Euler 问题的一部分.无论如何,我已经以更好的方式解决了这个问题,但这仍然让我烦恼,因为该函数似乎可以正常工作 - 并且它似乎知道我想要返回的变量的值.

It was part of my solution to a Project Euler problem. I have solved the problem in a better way anyhow, but this is still annoying me as the function seems to work OK - and it seems to know the value of the variable I wanted to return.

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.

But if I uncomment the return statement it only returns a value if the first try is prime, otherwise it returns None.

推荐答案

当找不到质数时忘记返回值:

You forgot to return a value when there is failure to find a prime:

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)

不过,递归在这里并不合适.它并不比简单的迭代方法更优雅.此外,如果您遇到两个连续素数之间存在大量非素数的区域,您可能会溢出堆栈.

Recursion isn't really suitable here though. It isn't much more elegant than the simple iterative approach. Also, you could overflow the stack if you hit an area where there are lot of non-primes between two consecutive primes.

这篇关于Python 函数在递归后返回 None的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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