A list can be used to store a range of data, but it takes up memory if the amount of data is large. So there is a way to generator in addition to ordinary functions. The flag statement is yield.
Title Requirements:
Write a generator, genprimes, that returns the sequence of prime numbers on successive calls to its next () Method:2, 3, 5 , 7, 11, ...
Analysis:
Here's how to generate prime numbers. General if X is prime, then x%p! = 0 (P is all previous prime numbers)
First Write code:
def genPrimes(): primelist = [2,] yield 2 num = 3 flag = 0 while True: for p in primelist : if (num%p) == 0 : flag = 1 if flag == 1 : flag = 0 num += 1 else : yield num primelist.append(num) num += 1
In addition to this way of writing together, you can also write a function to interpret whether it is a prime number.
Other solution
def genPrimes(): n = 1 primesList = [] while True: n += 1 if all(n % i != 0 for i in range(n-1, 1, -1)): primesList.append(n) yield n
def genPrimes(): from itertools import count as cnt pl = [2] return (pl.append(i) or pl[-2] for i in cnt(3,2) if all(i%p for p in pl))
List all prime number Python using generators