0
由於某種原因,我試圖包裹我的頭圍繞循環與範圍。蟒蛇for循環與範圍()
代碼:
# 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
生產這種輸出(即素數多達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
]
這是第二個問題,關於這一點,我在這裏問,我不能爲生命我弄清楚這是如何工作的。有人可以一步一步地解釋(最好能夠使其可視化),這裏究竟發生了什麼。例如,爲什麼4
不會打印爲素數?由於x == i(即4 == 4)或x%i - > False True等於True。
您可能想嘗試類似http://www.pythontutor.com/visualize.html – jonrsharpe