Search code examples
pythonprimes

is_prime one liner in python


I tried writing a function that returns 'True' if the given parameter is a prime number and 'False' otherwise. In a sense, I achieved my goal but I just wanted to know of a better, more pythonic way to do it, here's what I came up with:

def prime_one_liner(n):
    return True if len([i for i in range(2,n) if n % i == 0]) == 0 else False

Solution

  • "Achieving Your 'Goal'"

    You cold use any to make it shorter if that is your goal:

    def prime(n): return not any(n % i == 0 for i in range(2,n))
    

    Although, "pythonic" is not how I would describe this. It is more like "hard to read." Yet, it may be more pythonic than your version.

    Better way:

    A more readable version would be:

    def prime(n): 
        for i in range(2, n): #for every value between 1 and n
            if n%i == 0: #check if i divides n
                return False #if this is true, n is not prime
        return True
    

    Proper Function:

    However you need to account for values less than 2 so you would also need to edit your code like so:

    def prime(n): return not any(n % i == 0 for i in range(2,n)) if n > 1 else False
    

    And/or:

    def prime(n): 
        for i in range(2, n): #for every value between 1 and n
            if n%i == 0: #check if i divides n
                return False #if this is true, n is not prime
        return True if n > 1 else False #values less than 2 are not prime.
    

    General Info:

    Your code will not work for all integer values of n, consider, n=1 (see the amended examples above that fix this issue), but regardless, it is possible to make it shorter if that is your goal (as shown above), but just because it is short does not mean it is "pythonic." Currently your code is quite hard to read. So maybe expanding the code would be better (similar to the code expansion above).