Michael Karkos
Michael Karkos

Reputation: 11

Python how to run this function to get 100 primes

I have this code I want to run:

def genPrimes():
    primes = []   # primes generated so far
    last = 1      # last number tried
    while True:
        last += 1
        for n in primes:
            if last % n == 0:
                break
    else:
        primes.append(last)
        yield last
n = genPrimes()

How would I implement this to return a list of 100 primes?

Upvotes: 1

Views: 93

Answers (3)

Daniel
Daniel

Reputation: 42768

This is a generator. If you correct the indentation, you can use it in a for-loop, or use islice to get the first 100 primes:

from itertools import islice

def genPrimes():
    primes = []   # primes generated so far
    last = 1      # last number tried
    while True:
        last += 1
        for n in primes:
            if last % n == 0:
                break
        else:
            primes.append(last)
            yield last

primes = list(islice(genPrimes(), 100))

Upvotes: 4

RobertB
RobertB

Reputation: 1929

This code is a bit cryptic. I also don't think it does anything.

Your else is attached to your while which would only execute if you hit a break. Clever but cryptic. However, you initialize your list to [] and then do a loop though it. Looping through an empty list skips the body of the loop, which means the break will never execute. Since the break will never execute, the generator will never yield anything.

Thus, this is an infinite loop that does nothing.

Upvotes: 1

Avi Mosseri
Avi Mosseri

Reputation: 1368

try: [n.next() for x in range(100)]

Upvotes: 1

Related Questions