Wait for bloom
时光不语,静待花开

1.需求:用filter删除1-100的素数

filter用法为filter(func,iterable);

  • a.变量为1-100,所以iterable =range(1,100)
  • b.过滤掉素数,保留非素数,素数为只能被1和自己整除的数,通过循环将能被其他整除的返回
1 #!/usr/bin/python
2 #返回非素数
3 def test(j):
4     for i in range(1,j):
5             if j%i==0 and i!=1:
6                 return j
7 x=filter(test,range(1,100))
8 for i in x:
9     print(i)
View Code

2.需求:用filter保留1-100的素数

filter用法为filter(func,iterable);

  • a.变量为1-100,所以iterable =range(1,100)
  • b.保留素数,素数为只能被1和自己整除的数,如上面,只是与上面相反,咱们通过一个状态参数来取反
 1 #!/usr/bin/python
 2 #返回素数
 3 def test(j):
 4     status = False
 5     for i in range(1,j):
 6             if j%i==0 and i!=1:
 7                 status = True
 8     if status == False:
 9         return j
10 x=filter(test,range(1,100))
11 for i in x:
12     print(i)
View Code

 

posted on 2024-01-24 18:39  Little-Girl  阅读(37)  评论(0)    收藏  举报