The third day of python study notes

  • function arguments
  • local and global variables
  • Recursive and anonymous functions
  • Higher order functions
  • Functional programming understanding

First, the various parameters of the function

Key parameters and positional parameters: Just remember that key parameters must be placed after positional parameters

#parameter problem
def test(x,y,z):
    print(x)
    print(y)
    print (z)
test(z=1,x=2,y=3)#2,3,1, the order of key parameters is not affected
test(1,2,3)#1,2,3, the order of positional parameters is the order of incoming
#test(1,y=2,4)#error, the key parameter must be placed after the positional parameter
test (1, z = 2, y = 2)

Non-fixed arguments (variadic arguments?): *args, **kwargs

#variable parameter
def test1(*args):#The number of formal parameters is not fixed
    print(args)
test1(1,2,3,4,5,)#The actual parameters are put into the tuple
# Combine positional parameters
def test2(x,*args):
    print(x)
    print(args)
test2 (1,2,3,4,5,6,7)
#Accept the variable parameters of the dictionary---keyword parameters
def test3(**kwargs):
    print(kwargs)
test3(name='sun',age='8',sex='M',tall="168")
test3(name='sun')
#combination use
def test4(name,**kwargs):
    print(name)
    print(kwargs)
test4 ('sun')
test4('sun',age=10)
test4('sun',age=10,sex="m")

def test5(name,age=10,**kwargs):
    print(name)
    print(age)
    print(kwargs)
test5('sun',24,hobby='sleep')
The position of test5('sun',sex='m',age=3)#age=3 can be placed later

def test6(name,age=18,*args,**kwargs):
    print(name)
    print(age)
    print(args)
    print(kwargs)
test6('sun',24,1,2,3,sex='m',hobby='sleep')#Note how the following *args are passed

Second, local variables and global variables

For variables such as numbers and strings, changes in parameters inside the function will not affect the value of global variables outside the function

#The problem with local variables
name='SYR'
def change_name(name):
    print('before change',name)
    name='syr'
    print('after change',name)
change_name(name)
print(name)

Results of the:

before change SYR
after change syr
SYR

If you insist on changing the global variable of the same name outside the function inside the function, you can declare global inside the function

school='CQPUT'
def change(name):
    global school# can modify global variables within the function
    school='cqput'
    print('before change',name,school)
    name='syr'
    print('after change',name)
change(name)
print('school',school)
#After adding global in front of local variables, you can modify global variables

Results of the:

before change SYR cqput
after change syr
school cqput

You can see that if shcool changes internally, it will directly change the school outside the function.

But for arrays, dictionaries, etc., the parameter changes inside the function will be directly reflected outside the function

#Lists, sets, dictionaries, etc. Modifications inside the function will also affect global variables
names=['sun','yue','ru']
def change_names():
    names[0]='grandchild'
    print(names)
change_names()
print(names)#namse is modified

Results of the:

['grandchild', 'yue', 'ru']
['grandson', 'yue', 'ru']

Third, recursive functions and anonymous functions

Features of recursive functions:

  1. There must be an explicit end condition
  2. Each time you enter a deeper recursion, the size of the problem is reduced from the last time
  3. The effect of recursion is very low, which may cause stack overflow (function calls are implemented through the stack)

Simple recursive example: binary search

#Author:Yueru Sun
def binary_search(dataset,find_num):
    print(dataset)
    if len(dataset)>1:
        mid=int(len(dataset)/2)
        if dataset[mid]==find_num:
            print('Found %d, at %d position'%(dataset[mid],mid))
        elif dataset[mid]>find_num:
            print('The number to find is on the left of %d'%dataset[mid])
            return binary_search(dataset[0:mid],find_num)
        else:
            print('The number to find is on the right of %d'%dataset[mid])
            return binary_search(dataset[mid+1:],find_num)

    else:
        if dataset[0]==find_num:
            print('find number')
        else:
            print('Search failed')
# data = [1, 3, 6, 7, 9, 12, 14, 16, 17, 18, 20, 21, 22, 23, 30, 32, 33, 35]
binary_search([1, 3, 6, 7, 9, 12, 14, 16, 17, 18, 20, 21, 22, 23, 30, 32, 33, 35],1)

Anonymous function:

It is the specified function that does not need to be displayed

Simple example:

#this code
def calc(n):
    return n**n
print(calc(10))
 
#replace with anonymous function
calc = lambda n:n**n
print(calc(10))

Combine map:

res = map(lambda x:x**2,[1,5,7,4,8])
for i in res:
    print(i)

Fourth, higher-order functions

A higher-order function is a function that takes another function as a parameter.

Simple example:

def add(x,y,f):
    return f(x) + f(y)
 
 
res = add(3,-6,abs)
print(res)

Commonly used map of higher-order functions:

>>> def f(x):
...     return x * x
...
>>> map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9])
[1, 4, 9, 16, 25, 36, 49, 64, 81]

Commonly used reduce of higher-order functions:

>>> def add(x, y):
...     return x + y
...
>>> reduce(add, [1, 3, 5, 7, 9])
25

Commonly used filter of higher-order functions:

And map()similarly, filter()also accepts a function and a sequence. and map()different, apply filter()the incoming function to each element in turn, and then decide to keep or discard the element according to the Truereturn Falsevalue

def is_odd(n):
    return n % 2 == 1
filter(is_odd, [1, 2, 4, 5, 6, 9, 10, 15])
# result: [1, 5, 9, 15]

Sort of commonly used higher-order functions:

The sorted() function is also a higher-order function, and it can also receive a keyfunction to implement custom sorting, such as sorting by absolute value size:

>>> sorted([36, 5, -12, 9, -21], key=abs)
[5, 9, -12, -21, 36]

  

5. Functional programming

https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/0014317848428125ae6aa24068b4c50a7e71501ab275d52000

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325028364&siteId=291194637