python小程序段

自行书写python中将字符床转换为整数的函数:

from functools import reduce

def str2int(s):
    def fn(x, y):
        return x * 10 + y

    def char2num(s):
        return{'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[s]
    return reduce(fn, map(char2num, s))
#或者使用lamda函数
"""
def str2int(s):
    return reduce(lamda x, y: x * 10 + y, map(char2num, s))
"""

print(str2int('13579'))   

13579

利用 map() 函数,把用户输入的不规范的英文名字,变为首字母大写,其他小写的规范名字。输入: ['adam', 'LISA', 'barT'] ,输出:['Adam','Lisa', 'Bart'] :

def normalize(name):
    name = name.lower()
    return name[0].upper() + str(name[1:])


L1 = ['adam', 'LISA', 'barT']
L2 = list(map(normalize, L1))
print(L2)    

['Adam', 'Lisa', 'Bart']

Python 提供的 sum() 函数可以接受一个 list 并求和,请编写一个 prod()函数,可以接受一个 list 并利用 reduce() 求积:

from functools import reduce

def prod(L):
    def mul(x, y):
        return x*y
    return reduce(mul, L)


print(prod([3, 5, 7, 9]))

945

利用 map 和 reduce 编写一个 str2float 函数,把字符串 '123.456' 转换成浮点数 123.456 :

from functools import reduce

def str2float(s):
    dot = False
    dit = 1

    def f(x, y):
        nonlocal dot
        nonlocal dit
        if y == '.':
            dot = True
            return x
        if dot:
            dit = dit/10
            return x + y*dit
        return x*10 + y

    def str2int(x):
        dict = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, '.': '.'}
        return dict[x]
    return reduce(f, map(str2int, s))


print('str2float(\'123.456\') =', str2float('123.456'))   

str2float('123.456') = 123.456

打印30以内的素数:

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 < 30:
        print(n)
    else:
        break

2
3
5
7
11
13
17
19
23
29

利用filter滤掉非回数:

def is_palindrome(n):
    return str(n) == str(n)[::-1]


output = filter(is_palindrome, range(1, 1000))
print(list(output))

[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]

filter() 的作用是从一个序列中筛出符合条件的元素。由于 filter() 使用了惰性计算,所以只有在取 filter() 结果的时候,才会真正筛选并每次返回下一个筛出的元素。

用一组 tuple 表示学生名字和成绩,用 sorted() 对上述列表分别按名字和成绩排序:

L = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)]

def by_name(t):
    return t[0].lower()

def by_score(t):
    return t[1]


L1 = sorted(L, key=by_name)
L2 = sorted(L, key=by_score, reverse=True)
print(L1)
print(L2)   

[('Adam', 92), ('Bart', 66), ('Bob', 75), ('Lisa', 88)]
[('Adam', 92), ('Lisa', 88), ('Bob', 75), ('Bart', 66)]

闭包的应用:

def count():
    fs = []
    for i in range(1, 4):
        def f():
            return i*i
        fs.append(f)
    return fs


f1, f2, f3 = count()
print(f1(), f2(), f3())

def count2():
    def f1(j):
        def g():
            return j*j
        return g
    fs = []
    for i in range(1, 4):
        fs.append(f1(i))
    return fs


f4, f5, f6 = count2()
print(f4(), f5(), f6())

9 9 9
1 4 9

image

python中的private用处

image

你可能感兴趣的:(python小程序段)