Prime Generator In Python
I am writing a prime generator, which is different from anyone in this link generator in Python generating prime numbers Here is my code def sequence(): i = 1 while True:
Solution 1:
The problem is that i
inside the lambda isn't "fixed"; when i
changes in the outside scope, the previously created lambda functions all use the new value, and so they all do the same check: see if the current value from sequence()
is divisible by the last found prime. Which they never are.
Wrapping it into another lambda
and then calling it so that the value of i
can be fixed works:
defprime_generator(n):
i = 2
it = sequence()
while i < n:
it = (lambda i: filter(lambda x: x % i, it))(i)
i = next(it)
yield i
Edit: also I don't believe your code (nor this) does yield 2, but that can be trivially fixed.
Post a Comment for "Prime Generator In Python"