Python学习基础(9):函数式编程

时间:2021-04-21 22:41:38

[0]:高阶函数,可以接受其他函数作为参数:

比如

def high_func(x,f):
            return f(x)*f(x+1)
high_func(-10,abs)

[1]map和reduce的练习,map用来将一个函数作用到一个序列的每一个element上面并且返回一个新的iterator.我们可以用list()将这个iterator变成list.reduce则可以将一个函数的结果作用到下一个元素上面,然后不停调用.

将一系列名字变成开头大写,后面小写

def normalize(L):
    def convert(name):
        return str.upper(name[0])+str.lower(name[1:])
    return list(map(convert,L))
print(normalize(['alll','dFFFF']))

获得乘积

from functools import reduce
def prod(L):
    def times(x,y):
        return x*y
    return reduce(times,L)
ans = prod([1,2,3,4,5])
print(ans)

将字符串变成float版本1:

from functools import reduce
def str2float(s):
    x,y = s.split('.')
    y = y[::-1]
    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]
    def compute(x,y):
        return x*10+y
    def compute2(x,y):
        return x/10+y 
    return reduce(compute,map(char2num,x))+reduce(compute2,map(char2num,y))/10

print(str2float('0.2345'))

将字符串变成float版本2,这个版本好一点,避免输入整数会出现bug.但是它用到了nonlocal变量.来确定小数点出现的位置.

from functools import reduce
def str2float(s):
    point = 0;
    def char2nums(s):
        return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9,'.':-1}[s]
    def to_float(f,y):
        nonlocal point
        if(y == -1):
            point = 1
            return f
        if (point == 0):
            return f*10+y
        else:
            point = 10*point
            return f+y/point
    nums = list(map(char2nums,s))
    return reduce(to_float,nums,0.0)
print(str2float('123'))