Try... except....Try again?

Jack Diederich jackdied at gmail.com
Fri Jul 17 11:02:09 EDT 2009


On Fri, Jul 17, 2009 at 10:35 AM, Xavier Ho<contact at xavierho.com> wrote:

> I changed my code to the following:
>
>     def nPrime(self, n):
>         "Returns nth prime number, the first one being 2, where n = 0. When
> n = 1, it returns 3."
>         for x in range(n+2):
>             try:
>                 return self.primes[n]
>             except IndexError:
>                 self.next()
>
> And it's definitely better. Thanks a ton guys.
>
> (n+2 because after looping the maximum number of times, it needs to try
> returning the value again.)

def nPrime(self, n):
    while len(self.primes) < n:
         self.next()
    return self.primes[n]

If you use an off-the-shelf prime number generator fucntion[1] that
returns consecutive primes the method collapses into a simple
function.

def nPrime(n, primes=[], next_prime=eratosthenes().next):
    while len(primes) < n:
        primes.append(next_prime())
    return primes[n]

-Jack

[1] http://www.catonmat.net/blog/solving-google-treasure-hunt-prime-number-problem-four/#comment-3075
     There is a deque implementation that is faster still but I can't
find a link.



More information about the Python-list mailing list