2017-08-09 18 views
0

以下程序 2 step 3 step 5 step 7 step產量的Python程序運行

結果如何運行的產量?什麼是收益回報,通過n或它的generator? 爲什麼不是9號的答案結果(2 step 3 step 5 step 7 step step)? 你能解釋一下程序是如何運行的嗎?

def _odd_iter(): 
    n = 1 
    while True: 
     n = n+2 
     yield n 

def _not_divisible(n): 
    return lambda x:x%n >0 

def primes(): 
    yield 2 
    it = _odd_iter() 
    while True: 
     print('step') 
     n = next(it) 
     yield n 
     it = filter(_not_divisible(n),it) 

c = primes() 
for i in c: 
    if i<10: 
     print(i) 
    else: 
     break 
+4

可能重複[「yield」關鍵字的作用是什麼?](https://stackoverflow.com/questions/231767/what-does-the-yield-keyword-do) –

+0

如果你想讓9出現,擺脫行'it = filter(_not_divisible(n),it)'。當然,那麼你不再發射素數... –

+0

@ivanrres我的帖子是否回答你的問題?如果不是,還不清楚什麼? – yogabonito

回答

1

程序在做什麼取決於for -loop在最後五行。循環正在消耗發生器c產生的素數(2,3,5,7,11,13,...)。

c不產生9,因爲9不是素數(它可以被3整除)。

而程序不打印11,13 ...因爲當i變成11(11不小於10)時退出for -loop。