1

I've written a code block to find n-th prime number.

For instance if n=2, then the result is 3 and if n=3, then 5 and so on. Below is my code.

def prime_or_not(n):
    for i in range(2, int(n ** 0.5)+1):
        if n % i == 0:
            return False
    else:
        return True

def get_first_n_prime(n):
    while True:
        if prime_or_not(n):
            yield n
        n += 1

def get_nth_prime_number(n, initial_number=2):
    count = 0
    for next_prime in get_first_n_prime(initial_number):
        count += 1
        if count < n:
            continue
        else:
            return next_prime

With the code above, I could get expected result. The question, however, is that I'm not sure whether this is pythonic way of using generator (with yield in a function). Any feedback or comment would be immensely helpful.

higee
  • 402
  • 1
  • 7
  • 16
  • 3
    If the code is complete and works, it's more appropriate to post it on Code Review. This site is primarily for fixing broken code. – Carcigenicate Mar 26 '17 at 11:49
  • Since your code is working, I suggest posting to code review (you could also see http://stackoverflow.com/questions/2211990/how-to-implement-an-efficient-infinite-generator-of-prime-numbers-in-python?rq=1) [Also: your naming isn't very pythonic... prime_or_not is a tautology [except possibly for n=1 because whether 1 is prime or not tends to be debatable], get_first_n_prime doesn't actually yield the n first primes but rather an infinite # of primes starting at n – Foon Mar 26 '17 at 11:50
  • 2
    I'm voting to close this question as off-topic because it's a better fit on code review. – President James K. Polk Mar 26 '17 at 13:49
  • Thanks, I wasn't just aware of the fact that only broken code was allowed on this platform. – higee Apr 14 '17 at 08:25

0 Answers0