I was trying to generate all prime numbers in range x to y. I tried simple example first: range(10,11)
which means to check if 10 is a prime number:
Here is my code:
prime_list = [x for x in range(10, 11) for y in range(2,x) if x % x == 0 and x % 1 == 0 and x % y != 0]
I know that the thing is missing the option to tell the expression that x%y != 0
should be checked for all y in range (2,x)
and return true if and only if all have met this condition.
How do we do that?
Use all
to check all elements (from 2 upto x-1) met conditions:
>>> [x for x in range(2, 20)
if all(x % y != 0 for y in range(2, x))]
[2, 3, 5, 7, 11, 13, 17, 19]
One way using set comprehension can be
list(set(range(2,11)) - {x for x in range(11) for y in range(2,x) if x%y == 0})
@falsetru's answer is correct. But also, attention should be paid to optimized code. As someone said in the the comments in Kasra's answer
In [227]: %timeit [x for x in range(4, 1000) if all(x % y != 0 for y in range(2, int(m.sqrt(x)) + 1))]
100 loops, best of 3: 2.08 ms per loop
In [228]: %timeit [x for x in range(4, 1000) if all(x % y != 0 for y in range(2, int(m.sqrt(x)) + 1))]
100 loops, best of 3: 2.09 ms per loop
In [229]: %timeit [x for x in range(4, 1000) if all(x % y != 0 for y in range(2, x-1))]
100 loops, best of 3: 10.4 ms per loop
In [230]: %timeit [x for x in range(4, 1000) if all(x % y != 0 for y in range(2, x-1))]
100 loops, best of 3: 10.3 ms per loop
The version with filter:
filter(lambda x:all(x % y != 0 for y in range(2, x)), range(2, 13))
Program to find prime numbers within a given range using list comprehensions:
min = 10
max = 100
primes = [num for num in range(min,max) if 0 not in [num%i for i in range(2,int(num/2)+1)]]
print (primes)