Getting the next smallest element in a Python collection

Eratosthenes sieve is a fairly quick way to generate prime numbers to the limit kas follows:

  • Start by typing p = (2, 3, 4, ..., k)and i = 2.
  • Starting with i^2, remove all multiples iof p.
  • Repeat for the next smallest iat p, until i >= sqrt(k).

My current implementation looks like this (with obvious optimization of pre-filtering all even numbers):

# Compute all prime numbers less than k using the Sieve of Eratosthenes
def sieve(k):
    s = set(range(3, k, 2))
    s.add(2)

    for i in range(3, int(sqrt(k)), 2):
        if i in s:
            for j in range(i ** 2, k, i * 2):
                s.discard(j)

    return sorted(s)

EDIT: Here is the equivalent code list:

def sieve_list(k):
    s = [True] * k
    s[0] = s[1] = False
    for i in range(4, k, 2):
        s[i] = False

    for i in range(3, int(sqrt(k)) + 2, 2):
        if s[i]:            
            for j in range(i ** 2, k, i * 2):
                s[j] = False

    return [2] + [ i for i in range(3, k, 2) if s[i] ]

It works, but not quite right. Rows:

for i in range(3, int(sqrt(k)), 2):
    if i in s:
        [...]

Find the next smallest element sby checking the membership of the set for each odd number. Ideally, the implementation should be:

while i < sqrt(k):
    [...]
    i = next smallest element in s

, set , , ( ) . list True/False , list True. list, 2.

? , - , O(1) ?

+5
2

, hashset. ; min(s) Pythonic ( O (n)).

collections.deque . deque . , , deque, , . O (1) ( n).

, , O (n) ( O (1) ), O (1) O (1) ; O (n) , (-) . , .

+6

. None . .

  • p = 2
  • p 'M'
  • p. , .

, , p None.

0

All Articles