python素数生成器
把两行注视间的it = filter(not_divisiable(n), it)换成it = filter(lambda x: x%n > 0, it) 为什么不行?def getodd():
n = 1
while True:
n = n+2
yield n
def not_divisiable(n):
return lambda x: x%n > 0
def prime():
yield 2
it = getodd()
while True:
n = next(it)
yield n
# -----------
it = filter(not_divisiable(n), it)
# -----------
for pn in prime():
if pn < 100:
print(pn)
else:
break
{:10_266:} 不要沉 >>> filter.__doc__
'filter(function or None, iterable) --> filter object\n\nReturn an iterator yielding those items of iterable for which function(item)\nis true. If function is None, return the items that are true.'
filter()函数内要有两个必要的参数:filter(function函数,sequence序列)
function函数是函数名不要加参数 lambda x
应该是不知道这个x,x未定义 看来还有很多东西要学习啊! 看来还有很多东西要学习啊! 先明白樓主所問的問題{:10_258:}{:10_258:}{:10_258:}{:10_258:}{:10_258:}{:10_258:}
加個 bool() 函數就能正常運行,代碼完全沒有問題,千萬不要只局限於眼前事物,多看多學多問
def getodd():
n = 1
while True:
n = n+2
yield n
def not_divisiable(n):
return lambda x: bool(x%n > 0)
def prime():
yield 2
it = getodd()
while True:
n = next(it)
yield n
# -----------
it = filter(not_divisiable(n), it)
# -----------
for pn in prime():
if pn < 100:
print(pn)
else:
break
页:
[1]