Reputation:
For some reason I've hell of time trying to wrap my head around looping with ranges.
The code:
# inefficient way to compute primes with "filter"
nums = range(2, 100)
for i in range(2, 8):
"""Sieve of Eratosthenes:
Leave the element in the list if it is equal to "i",
or if it leaves a non-zero remainder when divided by "i".
"""
# (x % i returns either zero or non-zero, 0 -> False, non-0 -> True)
nums = filter(lambda x: x == i or x % i != 0, nums)
print nums
Producing this output (i.e. primes up to 100):
[
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
]
This is the second question regarding this I've asked here and I cannot for the life of me figure out how this works. Can someone explain, step by step (preferably so that it can be visualized) what's happening here exactly. For example why doesn't 4
get printed as a prime? Since x == i (i.e. 4==4) or x % i --> True of False equals True.
Upvotes: 0
Views: 290
Reputation: 96
Your code utilizes the Sieve of Eratosthenes method to identify prime numbers up to 100. It initializes a list named nums
containing numbers ranging from 2 to 99. Then, it executes a loop over the numbers 2 to 7. Within each iteration, a filtration process takes place using the filter
function alongside a lambda expression. This operation eliminates numbers from nums
that are divisible by the current value of i
or identical to i
itself. Following each iteration, nums
is updated to retain solely the remaining prime numbers. Numbers like 4 are dropped from the final result as they are recognized as composite during the filtration procedure due to their divisibility by 2.
Upvotes: 0
Reputation: 599470
You're missing the fact that nums
is getting filtered on every iteration. So, on the first iteration, all numbers for which x % 2 is not 0 - which includes 4 - are filtered out.
If you put an extra print nums
within the loop, after the filter, you would see this more clearly.
Upvotes: 3