Detailed explanation 3_ Recursion_ Anonymous function - function - python

Keywords: Python function recursion

1. Recursion

The programming technique of a program calling itself is called recursion.
As an algorithm, recursion is widely used in programming languages. A procedure or function has direct or indirect meaning in its definition or description
A method of indirectly calling itself, which usually transforms a large and complex problem layer by layer into a smaller problem similar to the original problem
The recursive strategy only needs a small number of programs to describe the multiple repeated calculations required in the problem-solving process, which greatly reduces the amount of code in the program.
The ability of recursion is to define an infinite set of objects with limited statements. Generally speaking, recursion needs boundary conditions and recursion forward
Segment and recursive return segment. When the boundary conditions are not satisfied, recursively advance; When the boundary conditions are met, it returns recursively.

  • characteristic
  1. There must be a clear end condition
  2. Each time you enter a deeper recursion, the problem size (Computation) should be reduced compared with the last recursion
  3. The recursive efficiency is not high. Too many recursive levels will lead to stack overflow (in computer, function calls are realized through the data structure of stack. Every time a function call enters, the stack will add one layer of stack frame, and every time the function returns, the stack will reduce one layer of stack frame. Because the size of the stack is not infinite, too many recursive calls will lead to stack overflow)
  • Noun analysis

    • Recursion: as disassembled by the above recursive implementation, each recursion is based on the last execution, which is called recursion
    • Backtracking: when a termination condition is encountered, it returns the value level by level from the last. This is called backtracking
  • case

    1. Factoring

      def factorial(n):
          '''
          seek n factorial 
          :param n:   A given natural number
          :return:    n factorial 
          '''
          if n == 1 or n == 0:
              return 1
          else:
              return n * factorial(n - 1)
      
      
      r = 5
      print('{}The factorial of is:{}'.format(r, factorial(r)))
      
      
    2. Fibonacci sequence

      def fabonacci(n):
          '''
          Find the second order of Fibonacci sequence n term
          :param n:   Number of sequence items
          :return:    The first n term
          '''
          if n == 1 or n == 2:
              return 1
          else:
              return  fabonacci(n - 1) + fabonacci(n - 2)
      
      
      r = 15
      print('Fibonacci sequence No{}Items are:{}'.format(r, fabonacci(r)))
      
  • Reference address: Classic case of Python recursion

2. Anonymous function

In Python, functions defined by lambda keyword instead of def are called anonymous functions.

lambda function can receive any number of parameters (which can be 0), but can only return the value of one expression. lambda function is a function object, which is directly assigned to a variable, which becomes a function object.

Syntax: lambda Parameter lists: expressions

First write the lambda keyword, and then write the parameters of the anonymous function in turn. Multiple parameters are connected with commas, followed by a colon, followed by the returned expression.

Using lambda function can omit the definition of the function. You do not need to declare a function and then use it. Instead, you can directly use the function while writing the function.

  • Usage scenario:

1. When a function object needs to be passed as a parameter, you can directly define a lambda function (as a parameter or return value of the function)

2. The business to be processed conforms to the lambda function (any number of parameters and a return value), and this function will only be used in one place and will not be reused in other places. Lambda function can be used

3. Use it with some Python built-in functions to improve the readability of the code

2.1 comparison between anonymous functions and ordinary functions

def test01(n):
    return n ** 2


# Anonymous function
f = lambda n: n ** 2
n = 5
print('{}The square of is:{}'.format(n, test01(n)))
print('{}The square of is:{}'.format(n, f(n)))
  • Anonymous functions are used only once
  • Normal functions are suitable for multiple calls
  • lambda functions are more concise than ordinary functions and do not declare function names

2.2. Multiple forms of anonymous functions

# No parameters
lambda_a = lambda: 100
print(lambda_a())
 
# One parameter
lambda_b = lambda num: num * 10
print(lambda_b(5))
 
# Multiple parameters
lambda_c = lambda a, b, c, d: a + b + c + d
print(lambda_c(1, 2, 3, 4))
 
# Expression branch
lambda_d = lambda x: x if x % 2 == 0 else x + 1
print(lambda_d(6))
print(lambda_d(7))

As you can see, lambda can have 0 to more parameters, and the returned expression can be a complex expression, as long as the last value is a value.

2.3. Anonymous function as parameter

def test(n, f):
    return f(n)


n = 5
print('{}The square of is:{}'.format(n, test(5, lambda n: n ** 2)))
print('{}The third power of is:{}'.format(n, test(5, lambda n: n ** 3)))

2.4. lambda functions are used in conjunction with Python built-in functions

  • Common functions
Function namefunction
max(*args, key=None)Find the maximum value
min(*args, key=None)Find the minimum value
sorted(object)sort
filter(object)filter
map(object)transformation
reduce(object)Compress a sequence to get a value
member_list = [
    {"name": "Breezy", "age": 99, "power": 10000},
    {"name": "No cliff", "age": 89, "power": 9000},
    {"name": "wang chongyang", "age": 120, "power": 8000}
]
new_list = sorted(member_list, key=lambda dict_: dict_["power"])
print(new_list)

number_list = [100, 77, 69, 31, 44, 56]
num_sum = list(map(lambda x: {str(x): x}, number_list))
print(num_sum)

Operation results:

[{'name': 'wang chongyang', 'age': 120, 'power': 8000}, {'name': 'No cliff', 'age': 89, 'power': 9000}, {'name': 'Breezy', 'age': 99, 'power': 10000}]
[{'100': 100}, {'77': 77}, {'69': 69}, {'31': 31}, {'44': 44}, {'56': 56}]
  • Sorted is a built-in function for sorting lists in Python. We use lambda to get the sorted key.

  • Map is a built-in function used for mapping in Python. It receives two parameters. The first parameter is a function and the second parameter is an iteratable object. Map will traverse the values of the iteratable object and then pass the values to the function for execution in turn. We use lambda to implement the function parameters in the map.

2.5. lambda as return value of function

def run_func(a, b):
    return lambda c: a + b + c

return_func = run_func(1, 10000)
print(return_func)
print(return_func(100))
Operation results:

<function run_func.<locals>.<lambda> at 0x00000254E4C94158>
10101

Anonymous functions can be used as the return value of a function. In the above code, run_func returns an anonymous function and a function object. When we execute this function, we can get the result of lambda function.

  • Note: the parameters a and B are run_func, but we execute the returned function return_func is no longer in run_func is out of scope, and lambda functions can still use a and B parameters. The lambda function will save a copy of its running environment until it is executed by itself.

  • Reference address: Use of Python anonymous function lambda

Code warehouse address: https://gitee.com/gaogzhen/python-study

Posted by cidesign on Sun, 28 Nov 2021 23:31:34 -0800