Search code examples
pythonprimespython-itertools

Closest prime problem: What is this part of code doing? next(x for x in count(0) if isPrime(s+x) )


I was checking the solutions for a codewars kata, related to getting the closest prime number. Here is the link of the kata for more information. Transform to Prime

But I didn't understand the solution of a user, who made this:

from itertools import count

def isPrime(n):
    return n == 2 or n%2 and all(n%x for x in range(3,int(n**.5)+1,2))

def minimum_number(numbers):
    s = sum(numbers)
    return next(x for x in count(0) if isPrime(s+x))

What is doing the function next(x for x in count(0) if isPrime(s+x)) ? Because the count(0) doesn't make sense to me.


Solution

  • First, count(0) just returns an infinite iterator that starts at 0 and never stops (ie: 0, 1, 2, 3, 4, on and on forever).

    The user then uses x for x in count(0) if isPrime(s+x) to create a generator around this infinite iterator, using a generator expression. The syntax of generator expressions are pretty straight-forward: for every output x from count(0) that makes isPrime(s+x) true, output x. Basically, the original count() iterator is filtered to only the outputs which satisfy the condition isPrime(s+x).

    Finally, the user uses the next() function on that generator, which gets the next output of that generator. Because the generator is being freshly created from that generator expression, this is just the first number that the generator produces. Or, the first non-negative integer value of x which makes isPrime(s+x) return True.