python 高级特性之filter实例代码

example01.py

# -*- coding: utf-8 -*-
"""
高级特性:filter
"""
#在一个list中,删掉偶数,只保留奇数,可以这么写:
def is_odd(n):
    return 0 == n%2
s = list(filter(is_odd,[1,2,3,4,5,6,7,8,9,10]))
print(s)  

#把一个序列中的空字符串删掉
def not_empty(s):
    return s and s.strip()
s = list(filter(not_empty, ['A', '', 'B', None, 'C', '  ']))
print(s)

#注意到filter()函数返回的是一个Iterator,也就是一个惰性序列,
#所以要强迫filter()完成计算结果,需要用list()函数获得所有结果并返回list。

example02.py

# -*- coding: utf-8 -*-
"""
Created on Mon Oct 15 20:17:20 2018

@author: 28358

计算素数的一个方法是埃氏筛法,它的算法理解起来非常简单:

首先,列出从2开始的所有自然数,构造一个序列:

2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, ...

取序列的第一个数2,它一定是素数,然后用2把序列的2的倍数筛掉:

3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, ...

取新序列的第一个数3,它一定是素数,然后用3把序列的3的倍数筛掉:

5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, ...

取新序列的第一个数5,然后用5把序列的5的倍数筛掉:

7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, ...

不断筛下去,就可以得到所有的素数。

用Python来实现这个算法
"""
#可以先构造一个从3开始的奇数序列:
def _odd_iter():
    n = 1
    while True:
        n = n + 2
        yield n

#然后定义一个筛选函数:
def _not_divisible(n):
    return lambda x: x % n > 0
    
#最后,定义一个生成器,不断返回下一个素数:
def primes():
    yield 2
    it = _odd_iter() #初始序列
    while True:
        n = next(it)
        yield n
        it = filter(_not_divisible(n), it)


for n in primes():
    if n < 1000:
        print(n)
    else:
        break

example03.py

# -*- coding: utf-8 -*-
"""
回数是指从左向右读和从右向左读都是一样的数,例如12321,909。
请利用filter()筛选出回数
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 22, 33, 44, 55, 66, 77, 88, 99, 101, 111, 121, 131, 141, 151, 161, 171, 181, 191, 202, 212, 222, 232, 242, 252, 262, 272, 282, 292, 303, 313, 323, 333, 343, 353, 363, 373, 383, 393, 404, 414, 424, 434, 444, 454, 464, 474, 484, 494, 505, 515, 525, 535, 545, 555, 565, 575, 585, 595, 606, 616, 626, 636, 646, 656, 666, 676, 686, 696, 707, 717, 727, 737, 747, 757, 767, 777, 787, 797, 808, 818, 828, 838, 848, 858, 868, 878, 888, 898, 909, 919, 929, 939, 949, 959, 969, 979, 989, 999]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 22, 33, 44, 55, 66, 77, 88, 99]

"""

def is_palindrome(n):
    s = str(n)
    half = int(len(s)/2)
    for x in range(half):
        if s[x] != s[-1-x]:
            return False
    return True
    #pass True的留下 False的去除
    #return True
    #return False

s = list(filter(is_palindrome, [x for x in range(1000)]))
print(s)

def tracts(n):
    i = 1
    while True:
        t = str(i)
        if t==t[::-1]:
            yield i
        i = i + 1
        if i > n:
            break
        
print(list(tracts(100)))



posted @ 2018-10-15 20:55  cloudren2020  阅读(174)  评论(0编辑  收藏  举报