Finding prime numbers using list comprehention

后端 未结 5 574
迷失自我
迷失自我 2020-12-16 17:55

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

相关标签:
5条回答
  • 2020-12-16 18:39

    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]
    
    0 讨论(0)
  • 2020-12-16 18:45

    The version with filter:

    filter(lambda x:all(x % y != 0 for y in range(2, x)), range(2, 13))
    
    0 讨论(0)
  • 2020-12-16 18:49

    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})
    
    0 讨论(0)
  • 2020-12-16 18:58

    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)
    
    0 讨论(0)
  • 2020-12-16 19:01

    @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
    
    0 讨论(0)
提交回复
热议问题