Python学习札记(二十二) 函数式编程3 filter & SyntaxError: unexpected EOF while parsing
参考:
Problem
SyntaxError: unexpected EOF while parsing
遇到该语法错误,一般是由于 括号不匹配 问题。
Note
1.filter 用于过滤list,关键在于正确实现一个“筛选”函数。
eg.过滤得到偶数:
#!/usr/bin/env python3
L = []
# input 10 integers
for i in range(10) :
L.append(int(input()))
# define filter function => bool judge
def filter_func(x) :
return x%2 == 1
print(list(filter(filter_func, L)))
sh-3.2# ./filter1.py
10
9
8
7
6
5
4
3
2
1
[9, 7, 5, 3, 1]
filter function 是过滤判断函数,当返回为True时执行过滤。
2.filter()函数返回的是一个Iterator,也就是一个惰性序列,所以要强迫filter()完成计算结果,需要用list()函数获得所有结果并返回list。
3.埃式筛法:
#!/usr/bin/env python3
# define a filter function
def filter_func(x) :
return lambda i: i%x > 0
# Iterator A: Initial Array
def creater() :
n = 1
while True:
n = n+2
yield(n)
def E_primes() :
yield(2)
it = creater() # Initial array
while True:
n = next(it) # iterator => next()
yield(n)
it = filter(filter_func(n), it) # creat new array
def main() :
primes = []
for i in E_primes() :
if i <= 1000 :
primes.append(i)
else :
break
print(primes)
if __name__ == '__main__':
main()
[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]
练习
回数是指从左向右读和从右向左读都是一样的数,例如12321,909。请利用filter()滤掉非回数:
#!/usr/bin/env python3
def is_palindrome(n) :
i, j, cnt = n, n, 0
while i > 0 :
cnt = cnt+1
i = int(i/10) # hint
ans = True
s = str(j)
for i in range(0, cnt) :
if s[i] != s[cnt-1-i] :
ans = False
break
return ans
def main() :
output = filter(is_palindrome, range(1, 1000))
print(list(output))
if __name__ == '__main__':
main()
sh-3.2# ./filter3.py
[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]
2017/2/14
To improve is to change, to be perfect is to change often.