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.