Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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:
        i += 2
        yield i

def prime_generator(n):
    i = 2
   it = sequence()
    while i < n:
        it= filter(lambda x: x % i, it)
        i = next(it)
        yield i

when i run something like

for i in prime_generator(50):
    print(i)

It never dump 15, 33, sth like that for me. In a word, It gives me 2 and all odd numbers. what goes wrong here?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
139 views
Welcome To Ask or Share your Answers For Others

1 Answer

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:

def prime_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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...