Analysis of Anonymous function and Recursive thought in Python
This article focuses on "Anonymous functions and Recursive thought Analysis in Python". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn "Anonymous functions and Recursive thought Analysis in Python".
Anonymous function
First of all, let's briefly review:
Definition of the function:
Def function name (parameter): specific function statement block return [data to be returned]
Execution of the function:
# the function is executed only when it is called, and the function can execute the function name multiple times ()
Local and global variables:
Different functions have different scopes
Def test1 (): name = 'XXX' print (name) def test2 (): name =' YYY' print (name) test1 () test2 () locally you want to use a global variable to use the global variable name locally and still use the global variable local variable globals () ['variable name']
There is also a case where the function is nested with the variables that the function wants to use the last layer function.
Def test1 (): name = 'XXX' def test2 (): # use the variables above and print and view nonlocal name print (name) # call the function test1 to execute test2 test2 () test1 () # directly calling test2 will throw an exception test2 undefined # test2 ()
Because there are spaces in the arrows, Python also determines the scope based on this format and can only be called at the same level as the red box.
Returns another function within one function:
Def test1 (): print ("in the test1") def test2 (): print ("in the test2") return test1 () test2 ()
To explain the above code clearly, let's insert a recursion.
The property of recursion:
Recursion is to call yourself.
There must be a clear end condition, otherwise it will cause stack overflow
The number of recursive problems decreases each time.
Recursion is not efficient, but sometimes it really works.
Let's have the most classic Fibonacci array.
# the leader of the Fibonacci group is as follows: 1 pint 1, 2, 3, 5, 8, 13, 21, 34, 55. Def fabonacci (n): # end condition if n