Python functional programming

Posted by ntsf on Tue, 28 Dec 2021 19:36:26 +0100

1. Functional programming

Is to pass a function as an argument to another function

2. map function

You need two parameters, one is a function and the other is an iterator, and the result is used as a new iterator

The function is applied to each element of the iterator (in fact, there is a for loop by default), and the parameters received by the function are the elements of the iterator

2.1 reduce

Continue to merge the result with the next element of the sequence (equivalent to assigning the last result to this time, and then this time and the next operation).

a = ['adam', 'LISA', 'barT']
def f(i):
    return i.capitalize()
b = list(map(f, ['adam', 'LISA', 'barT']))#title case
print(b)

from functools import reduce
def m(x,y):
    return x*y
c = reduce(m,[3, 5, 7, 9])
print(c)

First, judge whether each character is a point. If not, return to shaping.

In fact, judge whether the returned character is a point. If not, return the calculation formula. If yes, x is returned, which is the result of the last run.

from functools import reduce


def c_f(x, y):
    if y != '.':
        return 10 * x + y
    else:
        return x


def is_point(cc):
    if cc != '.':
        return int(cc)
    else:
        return '.'


def _final(str):
    b = reduce(c_f, map(is_point, str))
    pLen = len(str) - str.find('.') - 1
    b = b / (10 ** pLen)
    print(b)


_final('12.345')

3. filter

Apply the passed in function to each value and return true or false

from functools import reduce

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

c = list(filter(c_f,list(range(1,100))))
print(c)

4. sorted

For sorting, you can use key=abs to specify sorting, or you can specify key as a function to accept each element as an input variable

def d(v):
    return v

L = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)]
b = sorted(L,key=d)
print(b)

5. Return function

It is called closure

Loop variables or variables with subsequent changes are prohibited in the return closure. However, the return function can be called in the new function

def lazy_sum(*args):
    def sum():
        ax = 0
        for n in args:#You can't do that
            ax = ax + n
        return ax
    return sum

 

def count():
    def f(j):
        def g():
            return j*j
        return g
    fs = []
    for i in range(1, 4):
        fs.append(f(i)) # f(i) is executed immediately, so the current value of i is passed into f()
    return fs

In a closure, the internal function has no permission to change the direction of the external function. You need to use nonlocal var. Or use the list

def c():
    l = [0]
    def cc():
        # nolocal a
        l[0] = l[0] + 1
        return l[0]
    return cc

6. Anonymous function

lambda x : x * x

That is, if x is passed in and x * x is returned, there can only be one return statement.

You can return the labmda function or pass the lambda function to a variable

7. Decorator

Do not change the encapsulated code and add new functions.

def now():
    print('2015-3-25')

def log(func):
    def wrapper(*args, **kw):
        print('call %s():' % func.__name__)
        return func(*args, **kw)#This step is to call the function
    return wrapper #This line just returns the function and does not call the function

d = log(now) #Note that now should also be used instead of d. This is just an example
d()

Now is the encapsulated code, and log is the newly created code, which is intended to add new functions to the now function

log(now): first d point to the log function space and execute the log function.

Return wrapper (return is not call), and d points to the wrapper space

When calling d, point to the wrapper space and execute the wrapper. At the same time, the function execution is returned, not the function.

8. Partial function

import functools
int2 = functools.partial(int, base=2)
int2('1000000')

After modifying the parameters of the existing python function, it becomes a new function

 

Topics: Python