Seventh Python basics functions, recursion, built-in functions

Source: Internet
Author: User
Tags define local variable scope lenovo

    • A mathematical-defined function and a function in Python
    • Second, why use a function
    • Background summary
    • Three functions and procedures
    • Four function parameters
    • Five local variables and global variables
    • Six forward reference ' function is variable '
    • Seven nested functions and scopes
    • Eight recursive calls
    • Nine anonymous functions
    • Ten-function programming
    • 11 Built-in functions
    • 12 Work in this section
A mathematical-defined function and a function in Python

Junior high School math function definition: Generally, in a change process, if there are two variables x and Y, and for each definite value of x, Y has a unique value corresponding to it, then we refer to x as the independent variable, y is called the dependent variable, Y is the function of X. The range of values of the argument x is called the definition field of the function.

such as Y=2*x

function definitions in Python: functions are a programmatic method of logical structuring and process.

1 Python function definition method: 2   3 def Test (x): 4     "the function definitions" 5     x+=1 6     return x 7       8 def: Define the function's keyword 9 te ST: Function name 10 (): Can be defined as parameter 11 "": Document description (not necessary, but strongly recommend adding descriptive information for your function) X+=1: Generic code block or program processing logic return: Define return value


Call run: can be with parameters or without
Function name ()

Add:

1. Functions in programming languages are distinct from those of mathematical meanings, where functions in a programming language encapsulate a string of logic used to accomplish a particular function through a function name, and the mathematical definition of a function is an equation in which the equation enters the value of the dependent variable x and it gets a result y, This is similar to a programming language (it also passes in a parameter to get a return value), different functions with mathematical meanings, the same values are passed in, the results are necessarily the same and there is no modification of any variables (no modification of the state). While the functions in the programming language pass in parameters with the same return value that are not necessarily the same and can modify other global variable values (because the execution of a function a may depend on the result of another function B, B may get different results, even if you pass the same parameter to a, the result of a will certainly be different)

2. Functional programming is: first define a mathematical function (mathematical modeling), and then follow the mathematical model in the programming language to implement it. As for the benefits of how to do this and how to do it, look at the following functional programming.

Second why use function background feed

Now the boss let you write a monitoring program, monitor the system status of the server, when the use of indicators such as cpu\memory\disk more than the threshold of the e-mail alarm, you emptied all the knowledge, wrote the following code

Press CTRL + C to copy the code<textarea></textarea>Press CTRL + C to copy the code

The above code realizes the function, but even the neighbor old Wang also saw the clue, Lao Wang kindly touched the face of your son, said, you this duplicate code too much, every time the alarm to rewrite a piece of code, too low, so there are 2 problems:

    1. Too much code duplication, kept copy and paste not in line with high-end programmer temperament
    2. If you need to modify this code in the future, such as to join the mass function, then you need to use all the code in the place to modify it again

You think Lao Wang is right, you do not want to write duplicate code, but do not know how to do, Lao Wang seems to see your mind, at this time he picked up your son, smiled and said, in fact, it is very simple, just want to repeat the code extracted, put in a public place, a name, who want to use this code, the name of the call on the line As follows

def send mail (content)    #发送邮件提醒    connect a mailbox server to    send mail    off connection while     True:         If CPU utilization > 90%:        send mail (' CPU alert ')         if HDD uses space > 90%:        send mail (' HDD alert ')         if memory consumption > 80%:        Send mail (' Memory alarm ')

You look at the code written by Lao Wang, imposing a magnificent, majestic atmosphere, the code reveals a restrained arrogance, thought, Lao Wang this person is really not general, suddenly to his background more interested in, ask Lao Wang, these fancy play How do you know? Lao Wang kissed your son, smoothed out the beard that does not exist, lightly said, "The old man, when young, the division from the Kinsisa of the Silver Horn King", you listen to the "Silver Corner King" of the words, not by the Jiao body a shock, thought, true NB, no wonder the code written so 6, this "Silver Horn King" That year in the lake but named sizable the name of the big, but unfortunately later over-indulgence, died in 2016, it is a pity, only left his brother alone when the two brothers fought down the Jiangshan. At this time you look at the old king left the figure, feel your son and he more and more like ...

Summarize the benefits of using a function:

1. Code Reuse

2. Maintain consistency and ease of maintenance

3. Extensibility

Three functions and procedures

Procedure definition: A procedure is simply a function with no return value

So it looks like we're talking about why the functions that we introduced when we used the function didn't return a value, and no return value was the process, yes, but there was something magical in python.

1 def test01 (): 2     msg= ' Hello the Little Green frog ' 3     print msg 4   5 def test02 (): 6     msg= ' Hello Wudalang ' 7     Print msg 8     return msg 9  t1=test01 ()  t2=test02 ()  print ' from test01 Return is [%s] '%t117 print ' from test02 return is [%s] '%t2

Summary: The Python interpreter implicitly returns none when a function/procedure does not return a value using the definition returned by return.

So in Python that is, the process can also be counted as a function.

1 def test01 (): 2     Pass 3   4 def test02 (): 5     return 0 6   7 def test03 (): 8     return 0,10, ' hello ', [' Alex ', ' L B '],{' Wudalang ': ' lb '} 9  t1=test01 () one t2=test02 () t3=test03 ()  print ' from test01 return is [%s] : '%type (t1), t116 print ' from test02 return was [%s]: '%type (T2), t217 print ' from test03 return is [%s]: '%type (T3), T3

Summarize:

Number of return values = 0: Return None

Number of return values = 1: Return object

Number of return values >1: return tuple

Four function parameters

1. Parametric the memory unit is allocated only when called, releasing the allocated memory unit immediately at the end of the call. Therefore, the formal parameter is only valid inside the function. Function call ends when you return to the keynote function, you can no longer use the shape parametric

2. Arguments can be constants, variables, expressions, functions, and so on, regardless of the type of argument, and when making a function call, they must have a definite value in order to pass these values to the parameter. It is therefore necessary to use the assignment, input and other methods to get the parameters to determine the value

3. Positional parameters and keywords (standard call: Real participation parameter position one by one corresponds; keyword call: position without fixing)

4. Default parameters

5. Parameter groups

Five local variables and global variables variables defined in subroutines are called local variables, and variables defined at the beginning of a program are called global variables. The global variable scope is the entire program, and the local variable scope is the subroutine that defines the variable. When a global variable has the same name as a local variable: Local variables work within subroutines that define local variables, and global variables work in other places.
1 name= ' LHF ' 2  3 def change_name (): 4     print (' My name ', name) 5  6 change_name () 7  8  9 def change_name () :     name= ' All-in-one '     print (' My name ', name)-Change_name () print (name):     + def change_name () Global Name20     name= ' Handsome '     print (' My name ', name) @ change_name () print (name)
Six forward reference ' function is variable '
1 def Action (): 2     print ' In the action ' 3     Logger () 4 action () 5 error Nameerror:global name ' logger ' is not defined 6  7  8 def logger (): 9     print ' In the Logger ' Def action (): One     print ' in the action '     logger ()  1 4 action ()  def action (): print ' in the     action '     logger ()-Def logger ():     print ' in the Logg Er '  action ()
Seven nested functions and scopes

Looking at the title above means that the function can also be nested functions? Of course

1 name = "Alex" 2   3 def change_name (): 4     name = "Alex2" 5   6     def change_name2 (): 7         name = "Alex3" 8 Print         ("3rd print", name) 9     change_name2 () #调用内层函数11     print ("2nd layer", name)  14 Change_name () print ("Outermost printing", name)

At this point, what happens when you call Change_name2 () at the outermost layer?

Yes, it went wrong, why?

The scope is fixed when the function is defined and does not change as the call position changes

1 Example one: 2 name= ' Alex ' 3  4 def foo (): 5     name= ' LHF ' 6     def Bar (): 7         Print (name) 8     return Bar 9 Func=foo ( ) one func () 12 13 14 Case II: Name= ' Alex ', Def foo ():     name= ' LHF '     def Bar ():         name= ' Wupeiqi '         def TT ():             print (name),         Tt24     return bar25, Func=foo (), Func () ()

Eight recursive calls

The ancient desire Mingmingde in the world, first to govern his country, to govern his country, first to his home, to his family, to fix his body, to fix his body, to be his heart, to be his heart, to first be sincere, to be sincere, to know in phenomena. The object is then known to, know and then sincere, sincere and then Heart is, the heart is then body repair, body repair and then home, Home qi and then state governance, the state and then the world flat.

Inside a function, you can call other functions. If you call itself directly or indirectly during a call to a function

Press CTRL + C to copy the code<textarea></textarea>Press CTRL + C to copy the code
#_ *_coding:utf-8_*___author__ = ' linhaifeng ' import timeperson_list=[' Alex ', ' Wupeiqi ', ' Yuanhao ', ' Linhaifeng ']def Ask_way (person_list):    print ('-' *60)    if Len (person_list) = = 0:        return ' No one Knows '    Person=person_list.pop (0)    if person = = ' Linhaifeng ':        return '%s said: I know, the old boy is in Shahe Hui de commercial building, under the subway is '%person    print (' Hi-mei male [%s], dare to ask where the road is '%person ')    Print ('%s ' replied: "I don't know, but read your eyes to the pig, you wait, I help you ask%s ... '% (person,person_list))    Time.sleep (3)    Res=ask_way (person_list)    # print ('%s ' results were:%res '% (person,res))    Return Resres=ask_way (person_list) print (res)

Recursive properties:

1. There must be a clear end condition

2. Each time a deeper level of recursion is reached, the problem size should be reduced compared to the previous recursion

3. Recursive efficiency is not high, too many recursive hierarchy will lead to stack overflow (in the computer, function calls through the stack (stack) This data structure implementation, each time into a function call, the stack will add a stack of frames, whenever the function returns, the stack will reduce the stack frame. Because the size of the stack is not infinite, there are too many recursive calls, which can cause the stack to overflow.

Stack Literacy http://www.cnblogs.com/lln7777/archive/2012/03/14/2396164.html

Tail recursion optimization: http://egon09.blog.51cto.com/9161406/1842475

data = [1, 3, 6, 7, 9,, +, +, (+), (+), (+), (+), (+), (+), + (+), +/--  ) def binary_search (dataset,find_num):    PR Int (DataSet)     if Len (DataSet) >1:        mid = Int (len (DataSet)/2)        if dataset[mid] = = Find_num:  #find it            print ("Find number", Dataset[mid])        elif Dataset[mid] > Find_num: # Find the number on the left of mid            print ("\033[31;1m find the number in mid[%s] Left \033[0m "% dataset[mid])            return Binary_search (Dataset[0:mid], find_num)        else:# Find the number on the right of mid            print (" \ 033[32;1m find the number on mid[%s] to the right \033[0m "% dataset[mid])            return Binary_search (dataset[mid+1:],find_num)    else:        if dataset[0] = = Find_num:  #find it            print ("Find numbers", dataset[0])        else:            print ("No points, numbers to find [%s] ] Not in the list "% Find_num)  Binary_search (data,66)
Nine anonymous functions

An anonymous function is one that does not require an explicit function to be specified

1 #这段代码2 def calc (n): 3     return N**N4 print (Calc) 5  6 #换成匿名函数7 calc = lambda n:n**n8 print (Calc (10))

You may say that it is not convenient to use this thing. Oh, if it is so used, there is no yarn improvement, but the anonymous function is mainly used with other functions, as follows

1 l=[3,2,100,999,213,1111,31121,333]2 print (max (l)) 3 4 dic={' K1 ': Ten, ' K2 ': +, ' K3 ': 30}5 6 7 print (max (DIC)) 8 print (dic[ Max (Dic,key=lambda k:dic[k]))

1 res = map (lambda x:x**2,[1,5,7,4,8]) 2 for i in Res:3     print (i) 4  5 output 6 1 7 25 8 49 9 1610 64
Ten-function programming

Peak Brother original Process-oriented interpretation:

function parameters passed in, is the function to eat food, and the return value of the function return, is the result of the function pull out, the process-oriented idea is that the execution of the program as a string of functions, a function to eat, pull something to another function to eat, another function to eat and then continue to pull the next function to eat ...


For example:
User logon process: Front end receive processing user request-"Pass user information to logical layer, logical word processing user information-" Write user information to database
Verify the user logon process: Database query/processing user information-"to the logical layer, the Logic layer processing user Information-" User information to the front end, the front-end display of user information

Functional Programming:

http://egon09.blog.51cto.com/9161406/1842475

11 Higher order functions

Satisfies two characteristics either one is the higher order function

1. The passed-in parameter of the function is a functional name

2. The return value of a function is a functional name

Array=[1,3,4,71,2]ret=[]for i in array:    ret.append (i**2) print (ret) #如果我们有一万个列表, you can only define the above logic as a function def map_test ( Array):    ret=[]    for i in array:        ret.append (i**2)    return Retprint (map_test (array)) #如果我们的需求变了, Not to put each element in the list squared, plus 1, minus one, then you can do this def add_num (x):    return x+1def map_test (func,array):    ret=[] for i in    array:        Ret.append (func (i))    return Retprint (Map_test (Add_num,array)) #可以使用匿名函数print (Map_test (lambda X:x-1,array) #上面就是map函数的功能, map results in an iterative object print (Map (lambda X:x-1,range (5)))
From functools import reduce# Merge, a combined result Array_test=[1,2,3,4,5,6,7]array=range (#报错啊), RES does not specify the initial value def reduce_test ( Func,array):    l=list (array)    for I in L:        res=func (res,i)    return res# print (reduce_test (Lambda x,y:x+y, Array)) #可以从列表左边弹出第一个值def reduce_test (func,array):    l=list (array)    Res=l.pop (0) for    i in L:        Res=func ( Res,i)    return Resprint (reduce_test (lambda x,y:x+y,array)) #我们应该支持用户自己传入初始值def reduce_test (func,array,init=none ):    l=list (array)    if Init is None:        res=l.pop (0)    else:        res=init for    i in L:        res=func (res,i)    Return Resprint (Reduce_test (lambda X,y:x+y,array)) print (Reduce_test (lambda x,y:x+y,array,50))
#电影院聚集了一群看电影bb的傻逼, let's Find Them movie_people=[' Alex ', ' Wupeiqi ', ' Yuanhao ', ' Sb_alex ', ' Sb_wupeiqi ', ' Sb_yuanhao ']def Tell_ SB (x):    return X.startswith (' SB ') def filter_test (Func,array):    ret=[] for    i in array:        if Func (i):            Ret.append (i) return    retprint (Filter_test (tell_sb,movie_people)) #函数filter, returns an iterative object, print (filter (lambda x: X.startswith (' SB '), movie_people))
#当然了, Map,filter,reduce, can handle all data types name_dic=[    {' name ': ' Alex ', ' age ': +},    {' name ': ' Wupeiqi ', ' Age ': 10000}    {' name ': ' Yuanhao ', ' Age ': 9000},    {' name ': ' Linhaifeng ', ' age ':], ' #利用filter过滤掉千年王八, perpetual Turtle, and a 9,000-year-old def func (x ):    age_list=[1000,10000,9000]    return x[' age ' "Not in Age_listres=filter (func,name_dic) for I in Res:    print (i) Res=filter (Lambda x:x[' age '] = = 18,name_dic) for I in Res:    print (i) #reduce用来计算1到100的和from functools Import Reduceprint (Reduce (lambda x,y:x+y,range)) print (Reduce (lambda x,y:x+y,range (1,101))) #用map来处理字符串列表啊, Turn everyone on the list to SB, for example alex_sbname=[' Alex ', ' Wupeiqi ', ' Yuanhao ']res=map (lambda x:x+ ' _SB ', name) for I in Res:    print (i)
11 Built-in functions

Dictionary operations: Min, max, sort salaries={    ' Egon ': '    Alex ': 100000000, '    Wupeiqi ': 10000,    ' Yuanhao ': 2000} Iteration Dictionary , obtained is key, so the comparison is the max and min value of key >>> max (salaries) ' Yuanhao ' >>> min (salaries) ' Alex ' can take values to compare >> > Max (salaries.values ()) 100000000>>> min (Salaries.values ()) 2000 but usually we want to take out the highest-paid name, which is the value of salaries, Get keys >>> max (Salaries,key=lambda k:salary[k]) ' Alex ' >>> min (salaries,key=lambda k:salary[k]) ' Yuanhao ' can also be implemented by means of a zip salaries_and_names=zip (salaries.values (), Salaries.keys ()) Compare the values first, the same values, compare keys >>> max ( Salaries_and_names) (100000000, ' Alex ') Salaries_and_names is an iterator and thus can only access once >>> min (salaries_and_names) Traceback (most recent):  File ' <stdin> ', line 1, in <module>valueerror:min () arg was an empty SE Quencesorted (Iterable,key=none,reverse=false)

Built-in Parameter details Https://docs.python.org/3/library/functions.html?highlight=built#ascii

12 Work in this section

Have the following employee information sheet

Of course, this table is what you can say when you store files

1 1,alex li,22,13651054608,it,2013-04-01

Now need to this employee information file, to achieve additions and deletions to change the operation

    1. For fuzzy queries, the syntax supports at least 3 of the following:
      1. Select Name,age from staff_table where age > 22
      2. SELECT * from staff_table where dept = "IT"
      3. SELECT * from staff_table where enroll_date like "2013"
      4. Find the information, after printing, the last side to show the number of found
    2. Can create a new employee record, with the phone to do unique keys, staff_id need to increase
    3. Delete a specified employee information record, enter an employee ID, and delete
    4. To modify employee information, the syntax is as follows:
      1. UPDATE staff_table SET dept= "Market" where where dept = "IT"

Note: The above requirements, to fully use the function, please do your utmost to reduce duplication of code!

Built-in function anonymous function recursive ===================== job # Use Map to process a list of strings Ah, the list of everyone into SB, for example alex_sbname=[' Alex ', ' Wupeiqi ', ' Yuanhao ']# Use map to process the following L, and then use list to get a new list, each person's name is SB end >>> l=[{' name ': ' Alex '},{' name ': ' Y '}]>>> x=map (lambda i:{' name ': i[' name ']+ ' SB '},l) >>> for i in x: ... print (i) ... {' name ': ' ALEXSB '} {' name ': ' YSB '}===================== job two # processed with filter to get stock price greater than 20 stock name shares={' IBM ': 36.6, ' Lenovo ': 23.2, ' Oldboy ': 21 .2, ' Ocean ':10.2,}>>> f=filter (lambda k:shares[k]>20,shares) >>> list (f) [' IBM ', ' Lenovo ', ' Oldboy ']===================== Job three # is as follows, each dictionary name corresponds to the stock name, shares corresponds to how many shares, price corresponds to the value of the stock portfolio = [{' Name ': ' IBM ', ' shares ' : +, ' price ': 91.1}, {' name ': ' AAPL ', ' shares ': +, ' price ': 543.22}, {' name ': ' FB ', ' shares ': $, ' price ': 21.09 }, {' name ': ' HPQ ', ' shares ': +, ' price ': 31.75}, {' name ': ' YHOO ', ' shares ': ' $ ', ' price ': 16.35}, {' name ': ' ACME ' , ' shares ': 115.65}]1:map, ' price ': An iterator that contains a number that refers to the total cost of buying each stock >>> M=map (lambda item: item[' shares ']*item[' Price '],l) 2: Based on 1 results, use reduce to calculate how much money was spent on buying these shares >>> R=reduce (lambda x,y:x+y,m) >> > r51009.753: What >>> f=filter (lambda item:item[' price ' > 100,l) is used to filter out the stock with a value greater than 100

Seventh Python-based function, recursive, built-in function

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.