Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Generator returning stop iteration?

I'm can't figure out why the output of this comes out as:

>  File "<pyshell#177>", line 6, in func
>     list.append(next(PrimeGen)) 
>  StopIteration

when it makes so much sense in my head!! Anyways basically i'm trying to make a Prime Generator using an ifprime function and a generator to collect the primes in a list.

This determines if prime and returns the value if it is, otherwise nothing.

def prime(x):
    if (2**(x-1))%x ==1:
        return x

This makes the generator that should return a list full of prime numbers up to x but instead gives the error above. I started list with a 2 inside it because the above function prime(x) doesn't consider 2 as a prime (so range would start at 3)

def func(x):
  count=0
  list=[2]
  PrimeGen = (prime(X) for X in range(3,x+1))
  while count<99:
      list.append(next(PrimeGen))
      count+=1
  print list

Could anybody explain why it doesn't work? Thank you in advance! V.

like image 793
Valentine Bondar Avatar asked Feb 27 '26 12:02

Valentine Bondar


1 Answers

Fewer than 99 values were generated. Use itertools.islice() instead of a loop.

like image 138
Ignacio Vazquez-Abrams Avatar answered Mar 02 '26 03:03

Ignacio Vazquez-Abrams



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!