Python学习笔记——filter()实现埃氏筛选

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/AliceGoToAnother/article/details/79071269

先介绍filter(fn(),series)函数,其中 fn() 是筛选函数,返回值是True /False,series是待筛选的序列,filter()返回一个Iterator,也就是惰性序列。

#奇数序列生成器
def _odd_iter():
	n = 1
	while True:
		n += 2
		yield n
		
#筛选函数		
def is_notDivisable(n):
	return lambda x: x % n > 0

#奇数序列中筛选素数
def prime():
	yield 2
	it = _odd_iter()
	while True:
		n = next(it)
		yield n
		it = filter(is_notDivisable(n),it)

for  n in prime():
	if n < 1000:
		print(n)
	else:
		break



猜你喜欢

转载自blog.csdn.net/AliceGoToAnother/article/details/79071269