在使用python寻找质数的过程中,学习到了for...else...语句。
如果不用for...else...语句,应该这么写:
def genPrimes():
primes = [2]
prime = 2
num = 2
isPrime = True
while True:
if isPrime:
yield prime
num+=1
primeIndex = primes[:]
for i in primeIndex:
if num%i == 0:
isPrime = False
break
if i == primeIndex[-1]:
isPrime = True
prime = num
primes.append(num)
因为primes是在for循环中改变的,所以不能用primes作为for的条件,否则在执行primes.append(num)之后,我们期望是跳出for循环,开始考察下一个数是否是质数,但因为primes增加了一个成员,所以for循环会多执行一次,而这一次isPrime被改为False,永远无法yield prime。
而用了for...else...语句之后就简单许多:
# Note that our solution makes use of the for/else clause, which
# you can read more about here:
# http://docs.python.org/release/1.5/tut/node23.html
def genPrimes():
primes = [] # primes generated so far
last = 1 # last number tried
while True:
last += 1
for p in primes:
if last % p == 0:
break
else:
primes.append(last)
yield last