python 3.x - First 20 values that are true -


for n in range(561,1000): if n not isprime2(n) , isprimelike(n):     print(n,isprimelike(n)) 

i want function print first 20 values satisfy condition instead of printing whole range. once sees 20 values make condition true, stop.

first, i'm assuming typo: if n not isprime2(n) , isprimelike(n) makes no sense. want if not isprime2(n) , isprimelike(n)

to solve this, create generator comprehension condition out of loop:

(n n in range(561,1000) if not isprime2(n) , isprimelike(n)) 

(you don't need print isprimelike since true in case, filtered false values out)

then intergrate loop 20 times , 20 first iterations, in 1 line:

[next(n n in range(561,1000) if not isprime2(n) , isprimelike(n)) _ in range(20)] 

or (courtesy jon), using itertools.islice better if there aren't enough values (solution above throws stopiteration in case)

list(itertools.islice((n n in range(561,1000) if not isprime2(n) , isprimelike(n)),20)) 

Comments

Popular posts from this blog

neo4j - finding mutual friends in a cypher statement starting with three or more persons -

php - How to remove letter in front of the word laravel -

minify - Minimizing css files -