function, recursive function, return value scope, insert sort

Source: Internet
Author: User
Tags closure function definition variable scope

Function
Mathematical definition: y=f (x), Y is the function of x, and X is the independent variable. Y=f (x0, x1, ..., xn)
Python functions
A statement block, function name, and argument list consisting of several statements, which is a function of the smallest unit of the organization code.
Functions of the function
Structured programming for the most basic encapsulation of code, generally in accordance with the function of organizing a piece of code packaging for reuse, reduce redundant code code more concise and beautiful, readable and understandable
Classification of functions
Built-in functions such as Max (), reversed (), and other library functions such as Math.ceil (), etc.

def statement definition function
def function name (parameter list):
function body (code block)
[Return value]
The function name is the identifier, the name requirement is the same as the statement block must be indented, the Convention 4 spaces Python function does not have a return statement, implicitly return a value in the definition of the parameter list is a formal parameter, just a symbolic expression, called formal parameter
Call
function definition, just declare a function, it will not be executed, it needs to call the way, that is, the function name plus the parentheses, the parentheses are written on the arguments called when the arguments are actual parameters, is a real pass-through value, referred to as the argument

Parameters that are passed in when arguments are called match the number of definitions (variable parameter exceptions)
Position parameters
def f (x, Y, z) calls use F (1, 3, 5) to pass in arguments in the order in which they are defined
Keyword parameters
def f (x, Y, z) calls use F (x=1, y=3, z=5), using the name of the formal parameter to enter and exit the argument, and if the parameter name is used, then the order of the parameters can be different from the order of the definition
Pass the reference
F (Z=none, y=10, x=[1])
F ((1,), z=6, y=4.1)
F (y=5, z=6, 2) #
Requires that the positional parameter be passed in before the keyword parameter, which is the position parameter

Parameter default value (default)
When defined, follow a value after the formal parameter
def add (x=4, y=5):
Return X+y
Test calls Add (6, 10), add (6, y=7), add (x=5), add (), add (y=7), add (x=5, 6), add (y=8,
4), add (x=5, y=6), add (y=5, x=6)
Test definition The following function def add (x=4,y)
Role
The default value of a parameter can be assigned to a default value without a given parameter when sufficient arguments are not passed in
With very many parameters, it is not necessary for the user to enter all parameters each time, simplifying the function call
Example
Define a function login, the parameter name is called host, port, username, password

Variable parameters
A formal parameter can match any parameter
Variable parameters for positional parameters
There are multiple numbers that need to accumulate and sum
Using * Before the formal parameter indicates that the parameter is a mutable argument and can receive multiple arguments
Collect multiple arguments as a tuple
Variable parameters for keyword parameters
Use the * symbol before the formal parameter, indicating that you can receive multiple off
Mixed use of variable parameters
Summarize
Positional variable parameters and keyword variable parameters
Positional variable parameters use an asterisk before the formal parameter

Keyword variadic use two asterisk * before formal parameter * *
Positional variable parameters and keyword mutable parameters can all collect several arguments, position variable parameter collection form a tuple, close
Key-word variable-parameter collection forms a Dict
When mixing parameters, the variable parameter is placed at the end of the parameter list, and the normal parameter needs to be placed in front of the parameter list, bit
Variable parameters need to be preceded by the keyword variable parameter
Keyword-only parameters (Python3 added)
If after an asterisk parameter, or a positional variable parameter, the common parameters that appear are actually not normal
parameter, but the keyword-only parameter

Write a function, accept a parameter n,n is a positive integer, left and right two ways of printing. Require numbers to be aligned



return value of the function
The Python function returns the return value using the return statement
All functions have a return value and, if there is no return statement, implicitly calls return None
The return statement is not necessarily the last statement of a function's statement block
A function can have multiple return statements, but only one can be executed. If no return statement is
Line to, implicitly call return None
If necessary, you can display the call return None, which can be shortened to return
If the function executes the return statement, the function returns, and the other statements after the currently executed return statement are not
was carried out
Effect: End Function call, return value

function nesting
function nesting
Another function is defined in one function
The function has a visible scope, which is the concept of scopes
An intrinsic function cannot be used externally, it throws a Nameerror exception because it is not visible
Scope * * *
Scope
The visible range of an identifier, which is the scope of the identifier. Generally speaking, the scope of a variable
Global scope
Visible throughout the program's running environment
Local scope
Visible inside functions, classes, and so on
Local variables cannot be used beyond the local scope in which they reside
The example of nested structures shows that
Outer variable scope visible within scope of the inner layer
Global variables globally, variables using the global keyword
Global usage Principles
An outer scope variable is visible inside the scope, but not directly in the local scope of the inner domain, because
The purpose of the function is to encapsulate, as far as possible, isolated from the outside
If the function requires the use of an external global variable, use the function's parameter-pass argument to resolve
Free variable: A variable that is not defined in the local scope. For example, a variable that defines the scope of an outer function outside the memory function
Closures: A concept that appears in nested functions, meaning that the inner layer function refers to the free variable of the outer function, forming
The closure.
Using the nonlocal keyword, the variable is marked not defined in the local scope, but is defined in a level local scope of the ancestor, but does not
Can be defined in the global scope

Variable name resolution principle LEGB
Local, native scope, local namespace of the domain scope. When a function call is created
Build, call End extinction
enclosing,python2.2, the nested function is introduced, and the closure is implemented.
Is the namespace of the outer function of the nested function
Global scope, which is the namespace of a module. When the module is import
Create, the interpreter exits when extinct
Build-in, built-in module namespace, life cycle starts from the Python interpreter
When it is created, it dies when the interpreter exits. For example, print (open), print and open
is a built-in variable
So the search order for a noun is legb.

Insert Sort
Direct insertion Sorting principle
In an unordered sequence, build a sub-sort sequence until all data is sorted
Insert the number you want to sort into the appropriate position in the sorted sequence
Add a sentinel, place the value to compare, and compare it to the sequence that is already sorted, and find the right insertion point

anonymous functions
Anonymous, that is, no name.
anonymous function, which is a function without a name
No name how to define
No name how to call
If it can be called, how to use

anonymous functions
Use the Lambda keyword to define anonymous functions
Parameter list does not require parentheses
The colon is used to split the argument list and the expression
No need to use return, the value of the expression is the anonymous function return value
A lambda expression (an anonymous function) can only be written on one line, which is called a single-line function
Use
Lambda expressions are often used to simplify code when higher-order function parameters are passed

Recursive recursion
Recursive requirements
Recursion must have exit conditions, recursive calls must be executed to this exit condition. Recursive calls with no exit criteria are infinite
Call
The depth of recursive calls should not be too deep
Python limits the depth of recursive calls to protect the interpreter
exceeds recursion depth limit, throws recursionerror:maxinum recursion depth exceeded exceeds maximum depth
Degree
Sys.getrecursionlimit ()

Recursive performance
The loop is slightly more complex, but as long as it is not a dead loop, it can be iterated multiple times until the result is calculated
The FIB function code is very simple to understand, but can only get to the outermost function call, internal recursive results are intermediate results. And given an n
are nearly 2n recursive, the deeper the depth, the lower the efficiency. In order to get the Fibonacci sequence needed outside in the set an n cycles, the efficiency
It's even lower.
Recursive return has a depth limit, if the recursive complex, function repeatedly stack, stack memory quickly overflow

Recursive summary
Recursion is a natural expression that fits logical thinking.
Recursive relative operation efficiency is low, each call function to open up the stack frame
Recursion has a depth limit, and if the recursive hierarchy is too deep and the function repeatedly presses the stack, the stack memory quickly overflows
If you have a finite number of recursion, you can use recursive calls, or use loops instead, the loop code is slightly more complicated, but as long as it's not
A dead loop that can be iterated multiple times until the result is calculated
The vast majority of recursion can be implemented using loops
Even if the recursive code is concise, but can not be used without recursion

function, recursive function, return value scope, insert sort

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.