Python- Sieve of Eratosthenes- Compact Python

后端 未结 8 1286
醉话见心
醉话见心 2021-01-06 14:09

This is my code for finding primes using the Sieve of Eratosthenes.

list = [i for i in range(2, int(raw_input(\"Compute primes up to what number? \"))+1)]  
         


        
8条回答
  •  Happy的楠姐
    2021-01-06 14:18

    It's not precisely a direct translation of your loops, but it's quite close and compact:

    >>> l = range(2, 101)
    >>> sorted(set(l).difference(a for i in l for a in l if a!=i and a%i == 0))
    [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
    

    Although I'd suggest a > i rather than a != 0 as being shorter and faster ;)

提交回复
热议问题