Reputation: 19
Heres the code I'm trying to understand:
The code is the implementation of Sieve of Erastothenes. If I understand it correctly, then up to line 8, the code creates a list of prime numbers up to N and the list is a boolean list where True - prime; False - non-prime; and the index number matches with the number we output.
My question is: For lines 9-13 does the script "rewrite" the primes (which are just True values) with both the index and the boolean value in a new list in order for us to print them at the end? Also, if primes is a boolean list, why python prints the index values at the end instead of just a bunch of True arguments?
Update: I got it, thanks guys! range is a set of integers from 2 - n+1, hence i is integer as well, thats why I get integers in the primes string. For some reason I was thinking of range as list1 initialy
def sita(N):
list1 = [True for _ in range(N + 1)]
list1[0:1] = [False, False]
for start in range(2, N + 1):
if list1[start]:
for i in range(2 * start, N + 1, start):
list1[i] = False
primes = [] #create empty list
for i in range(2, N + 1):
if list1[i]:
primes.append(i)
return primes
print(sita(int(input("Dati un numar N: "))))
Upvotes: 0
Views: 810
Reputation: 155497
Your loop, for i in range(2, N + 1):
is looping over the actual indices. It tests the boolean value in list1[i]
, but only stores the index. The boolean value (list1[i]
) need not be written; the mere fact that you append
ed i
indicates that the test passed, and i
is known to correspond to a prime number. Since primes
is built from scratch, it contains no booleans at all, just the various i
values (tested and found prime) append
ed to it in the final loop.
Upvotes: 0
Reputation: 500663
primes.append(i)
only appends its argument, i
. There is no magic that would additionally append anything else to the list.
In your code, there are two separate, independent lists: list1
and primes
:
The first contains a boolean for each non-negative integer.
The second contains those integers for which list1
contained True
at the end of the first loop (this is what the if list1[i]
check does).
Upvotes: 0