-2

Hi I did this progrem to check if number is prime in 1 line and i didnt find anything about it.Everytime the False object in the set is first and the True is second. Is this some kind of rule? Here is the progrem that i wrote:

def is_prime(number):
    return set(([True if number % i != 0 else False for i in range(2, number)]))
print(is_prime(15))
alonybbb
  • 1
  • 1
  • False is zero and True is one. They naturally fall into that order when they're stored in hash buckets. – khelwood Nov 30 '21 at 18:35
  • 2
    By the way, your title says the opposite of what your question says. – khelwood Nov 30 '21 at 18:35
  • There are many efficiency gains available in the current prime checking method - if this meters to you. – S3DEV Nov 30 '21 at 18:38
  • Might be relevant: [Time complexity in sorting a list by converting it to a set and back into a list](https://stackoverflow.com/questions/61098519/time-complexity-in-sorting-a-list-by-converting-it-to-a-set-and-back-into-a-list) – MisterMiyagi Nov 30 '21 at 18:44
  • 1
    This is not a rule, this is an implementation detail – juanpa.arrivillaga Nov 30 '21 at 18:55

1 Answers1

0

Sets are unordered, so there is no difference between {False, True} and {True, False}. Either rendering is "correct", and you shouldn't build any assumptions around any particular ordering (even if in practice you see it rendered in sorted order -- AFAIK this is a property of the standard CPython implementation but is not a feature of the language, so it's subject to change without notice).

>>> {False, True} == {True, False}
True
>>> {False, True}
{False, True}
>>> {True, False}
{False, True}

You probably don't want to be returning a set from this function in the first place. Try using the all function to turn your generator expression into a single bool:

>>> def is_prime(number):
...     return all(number % i for i in range(2, number))
...
>>> is_prime(15)
False
>>> is_prime(7)
True

This produces equivalent results to if you were to test that your set only contains True:

>>> def is_prime(number):
...     return {True} == set(([True if number % i != 0 else False for i in range(2, number)]))

but is obviously much less code, and it also runs more quickly because it's not necessary to build the entire list in memory and turn it into a set; the all function stops reading values from the generator as soon as it hits the first False value.

Samwise
  • 68,105
  • 3
  • 30
  • 44