Discuss / Python / 用filter求素数--的疑问

### 用filter求素数--的疑问

Topic source

#### 沧海奇迹1

#1 Created at ... [Delete] [Delete and Lock User]

#定义一个筛选函数：

def _not_divisible(n):

return lambda x: x % n > 0

#### long8035

#2 Created at ... [Delete] [Delete and Lock User]

#### 沧海奇迹1

#3 Created at ... [Delete] [Delete and Lock User]

#### long8035

#4 Created at ... [Delete] [Delete and Lock User]

a = _not_divisible(n); it = filter(a,it)，这里it是迭代器，你可以把it看成一个无穷可数的序列(等价于生成器)，每次触发fitler就在序列中索引顺序递增地寻找一个数，使得其作为位置参数

it0=_odd_iter(); ｛n0 = next(it0); a0 = _not_divisible(n0); it1 = filter(a0,it0);  n1 = next(it1); a1 = _not_divisible(n1); it2 = filter(a1,it1); n2 = next(it2); a2 = _not_divisible(n2); it3 = filter(a2,it2); ...｝

prime()里面的while循环部分是yield产生式，故而可以描述上述大括号中的无穷嵌套过程，每循环一次，就把新获得的素数加进来通过%验证后面的数是否素数。

#### Gino_wang

#5 Created at ... [Delete] [Delete and Lock User]

def is_palindrome(n):

numSource = str(n)

antiNumSource = []

for v in numSource:

antiNumSource.insert(0,v)

antiNumSource = ''.join(antiNumSource)

#print(antiNumSource)

if numSource == antiNumSource:

return True

else:

return False

===================

def is_palindrome(n):

LSource = list(str(n))

LNow = []

for v in LSource:

LNow.insert(0,v)

if LSource == LNow:

return True

else:

return False

#### 华弦锦瑟

#6 Created at ... [Delete] [Delete and Lock User]

• 1