使用send修改生成器

时间:2019-02-20 22:04:11

标签: python generator

我想通过仅更改下面的handle_generator函数来修改生成器。这是一个人力资源挑战,这使我整天挠头。我想到了使用a previous SO question on even numbers发送的想法。我无法使用素数检查器上班。该算法应打印前10个非素数。目前正在打印3。

from math import sqrt
from itertools import count, islice

def is_prime(n):
    if n < 2:
        return False

    for number in islice(count(2), int(sqrt(n) - 1)):
        if n % number == 0:
            return False

    return True

# this is the only portion of the code that can be changed  
def manipulate_generator(generator, n):
     if not is_prime(n):
         generator.send(n+1)


#all the code below cannot be changed 
def positive_integers_generator():
    n = 1
    while True:
        x = yield n
        if x is not None:
            n = x
        else:
            n += 1

k = int(input())
g = positive_integers_generator()
for _ in range(k):
    n = next(g)
    print(n)
    manipulate_generator(g, n)

0 个答案:

没有答案