Jan-28-2022, 07:24 PM
In the Sieve of Eratosthenes example the prime list and sieve set are generated fresh each time the function is called. The user wants a list of prime numbers up to and including "n". The algorithm depends on generating a set of non-prime numbers. But even if you don't want a list there are lots of things you can do with a list. Sometimes creating a list may be the most efficient way to accomplish your goal.
Looking at your code it is unclear what you want to accomplish. If you just want to print the prime number in the range 0..20 the Sieve of Eratosthenes may be the most efficient way to do that.
If you really hate the idea of having a list, even as a temporary holder for your values, you could rewrite this as a generator.
Looking at your code it is unclear what you want to accomplish. If you just want to print the prime number in the range 0..20 the Sieve of Eratosthenes may be the most efficient way to do that.
def primes(n): # Sieve of Eratosthenes prime, sieve = [], set() for q in range(2, n+1): if q not in sieve: prime.append(q) sieve.update(range(q*q, n+1, q)) return prime for prime in primes(20): print(prime) # Because you want to print them one per line.The code is very efficient because it doesn't do any division or much math at all, far more efficient than using the modulo operator. This would be seen if n=1000000 instead of 20.
If you really hate the idea of having a list, even as a temporary holder for your values, you could rewrite this as a generator.
def primes(n): # Sieve of Eratosthenes sieve = set() for q in range(2, n+1): if q not in sieve: yield q sieve.update(range(q*q, n+1, q)) return prime for prime in primes(20): print(prime)Now primes() returns a number, not a list of numbers. It doesn't make much sense writing something like Sieve of Eratosthenes as a generator. The algorithm needs an ending point and making the ending point arbitrarily large makes the algorithm run very slow. But for many kinds of calculations or operations a generator is the way to go. You don't have to wait for it to compute every result, and it doesn't use a lot of storage to save results.