1、用filter求素数。

埃拉托色尼筛选法。

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
def _odd_iter():
n = 1
while True:
n = n + 2
yield n
# 这是一个从3开始的无限奇数序列 def _not_divisible(n):
return lambda x: x % n > 0
# 动态的筛选函数,如果不能被n整除就返回True def primes():
yield 2
it = _odd_iter()
while True:
n = next(it)
yield n
it = filter(_not_divisible(n), it) #不是n的倍数的留下! for n in primes():
if n < 1000:
print(n)
else:
break
D:\labs>python test.py
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
101
103
107
109
113
127
131
137
139
149
151
157
163
167
173
179
181
191
193
197
199
211
223
227
229
233
239
241
251
257
263
269
271
277
281
283
293
307
311
313
317
331
337
347
349
353
359
367
373
379
383
389
397
401
409
419
421
431
433
439
443
449
457
461
463
467
479
487
491
499
503
509
521
523
541
547
557
563
569
571
577
587
593
599
601
607
613
617
619
631
641
643
647
653
659
661
673
677
683
691
701
709
719
727
733
739
743
751
757
761
769
773
787
797
809
811
821
823
827
829
839
853
857
859
863
877
881
883
887
907
911
919
929
937
941
947
953
967
971
977
983
991
997

2、python中的lambda函数

lambda x:x%n>0

lambda语句中,冒号前的是参数,可以有多个,用逗号隔开,冒号右边的是返回值。

pyDay17的更多相关文章

随机推荐

  1. 怎样使用es6 export,import不会报错

    如果浏览器支持es6的话,需要加上type="module" <script type="module"> import Store from &q ...

  2. 解决Xcode "The selected destination does not support the architecture " 错误错误

    XCODE编译运行项目后,发现工程编译后无法运行,出现:"The selected destination does not support the architecture for whi ...

  3. 点击一个textView里的link导航至程序内可返回的自定义webView

    1,在AppDelegate.h里定义一个 id currentViewController; 在AppDelegate.m里 @implementation UIApplication (Priva ...

  4. PHP中str_replace和substr_replace有什么区别?

    两个函数的定义:(1)str_replace() 函数替换字符串中的一些字符(区分大小写). 该函数必须遵循下列规则: 如果搜索的字符串是一个数组,那么它将返回一个数组. 如果搜索的字符串是一个数组, ...

  5. LeetCode - Employees Earning More Than Their Managers

    Description: The Employee table holds all employees including their managers. Every employee has an ...

  6. 【BZOJ2157】旅游 树链剖分+线段树

    [BZOJ2157]旅游 Description Ray 乐忠于旅游,这次他来到了T 城.T 城是一个水上城市,一共有 N 个景点,有些景点之间会用一座桥连接.为了方便游客到达每个景点但又为了节约成本 ...

  7. 问答项目---账号密码异步校验后进行PHP校验

    在做登陆的时候,通过异步校验后还需要通过PHP来校验账号和密码的正确性. PHP校验账号密码: public function login(){ if(!IS_POST){echo "页面不 ...

  8. Hadoop命令别名

    [hadoop@master ~]$ alias hdfs='hadoop dfs' [hadoop@master ~]$ hdfs -ls / drwxrwxr-x   - hadoop super ...

  9. 升级mac xcode打包证书报错 git 报错

    reset tryAgain git 在钥匙串中找不到指定的项  重新配置公钥撕咬 SSH keys An SSH key allows you to establish a secure conne ...

  10. Django查询orm的前一天,前一周,一个月的数据

    利用datatime模块的datetime.timedelta()方法 计算时间差,以下是用法 唯一要注意的是数据库存储models.datefield字段是日期格式,所以比较的数据也是日期格式 #当 ...