Python function returning None after recursion

前端 未结 3 1647
栀梦
栀梦 2021-01-20 18:09

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

It was part of my solution to a Project Euler problem. I have solved the p

相关标签:
3条回答
  • 2021-01-20 18:47

    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.

    0 讨论(0)
  • 2021-01-20 19:05

    Notice that you are making recursive calls to the next_prime function, but not returning the value from it from the calling function.

    Replace the lines:

    print candidate, "is not prime - divisible by", div
    next_prime(candidate)
    

    with

    print candidate, "is not prime - divisible by", div
    return next_prime(candidate)
    
    0 讨论(0)
  • 2021-01-20 19:07

    As others have said, this is not really the place for recursion. Here is an example using iteration. I've also defined another function which tests the primality of an integer - I think this makes the code simpler.

    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)
    
    0 讨论(0)
提交回复
热议问题