鱼C论坛

 找回密码
 立即注册
查看: 3231|回复: 6

python素数生成器

[复制链接]
发表于 2017-10-19 21:40:15 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
把两行注视间的it = filter(not_divisiable(n), it)换成it = filter(lambda x: x%n > 0, it) 为什么不行?
  1. def getodd():
  2.         n = 1
  3.         while True:
  4.                 n = n+2
  5.                 yield n

  6. def not_divisiable(n):
  7.         return lambda x: x%n > 0

  8. def prime():
  9.         yield 2
  10.         it = getodd()
  11.         while True:
  12.                 n = next(it)
  13.                 yield n
  14.                 # -----------
  15.                 it = filter(not_divisiable(n), it)
  16.                 # -----------

  17. for pn in prime():
  18.         if pn < 100:
  19.                 print(pn)
  20.         else:
  21.                 break
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

 楼主| 发表于 2017-10-20 11:20:56 | 显示全部楼层
不要沉
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2017-10-20 11:41:25 | 显示全部楼层
>>> 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函数是函数名不要加参数
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2017-10-22 22:49:11 | 显示全部楼层
lambda x
应该是不知道这个x,x未定义
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2021-5-15 07:24:14 | 显示全部楼层
看来还有很多东西要学习啊!
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2021-5-18 21:13:29 | 显示全部楼层
看来还有很多东西要学习啊!
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2021-9-5 00:38:31 | 显示全部楼层
先明白樓主所問的問題

加個 bool() 函數就能正常運行,代碼完全沒有問題,千萬不要只局限於眼前事物,多看多學多問
  1. def getodd():
  2.         n = 1
  3.         while True:
  4.                 n = n+2
  5.                 yield n

  6. def not_divisiable(n):
  7.         return lambda x: bool(x%n > 0)

  8. def prime():
  9.         yield 2
  10.         it = getodd()
  11.         while True:
  12.                 n = next(it)
  13.                 yield n
  14.                 # -----------
  15.                 it = filter(not_divisiable(n), it)
  16.                 # -----------

  17. for pn in prime():
  18.         if pn < 100:
  19.                 print(pn)
  20.         else:
  21.                 break
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-7-12 19:42

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表