Improvement of prime generator

Example in Talk about ‘yield’ and ‘generators’

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34

def get_primes(number):
while True:
if is_prime(number):
number = yield number
number += 1

def is_prime(number):
if number > 1:
if number == 2:
return True
if number % 2 == 0:
return False
for current in range(3, int(math.sqrt(number) + 1), 2):
if number % current == 0:
return False
return True
return False

def print_successive_primes(iterations, base=10):
prime_generator = get_primes(base)
prime_generator.send(None) # 启动生成器

for power in range(iterations):
print(prime_generator.send(base ** power))

if __name__ == '__main__':
print_successive_primes(6)
# 2
# 11
# 101
# 1009
# 10007
# 100003

If I want to generate 10000 primes:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

def get_primes2(n):
p = 2
count = 0
while count <= n:
if is_prime(p):
yield p
count += 1
p += 1


def print_primes(n):
prime_generator = get_primes2(n)

for p in prime_generator:
print(p)

This way looks stupid…

1
2

# Thinking