2

I found this code to generate prime number in Python3:

def gen_primes(N):
    """Generate primes up to N"""
    primes = set()
    for n in range(2, N):
        if all(n % p > 0 for p in primes):
            primes.add(n)
            yield n

Here I have confusion with the line if all(n % p > 0 for p in primes). Since primes is initially blank, so the code inside "if" should never execute.

To become confident, I tried the code below and it is not executing the code inside the "for".

primes = set()
n=2
print("---------Outside For Loop--------")
for p in primes:
    print("---------Inside For Loop------")
    if all(n%p>0):
        print("Hello")
    else:
        print("No Way")

So I need expert help here to understand how this prime number generator working in this case?

TrebledJ
  • 8,713
  • 7
  • 26
  • 48

2 Answers2

2

Your test doesn’t demonstrate the issue because the function all is what you should inspect:

all([])
>>>True

By default all return Trie for empty lists, because unless all() finds a false In a list it returns true.

adir abargil
  • 5,495
  • 3
  • 19
  • 29
1

the all() function returns True if all items in an iterable are True, otherwise it returns False. If the iterable object is empty, the all() function also returns True.

I rewrote your function by replacing all() with v (which means validity) if the number is not prime (in other words it is not divisible by any number less than the number itself) v = 0 and is not included in the primes set.

def gen_primes(N):
primes = set()

for n in range(2,N+1):

    v = 1

    for nn in range(2,n):
        if(n%nn == 0):
            v = 0
            break
    
    if v: primes.add(n)

return primes

print(gen_primes(23))