Python-based built-in functions and recursion

Source: Internet
Author: User

First, built-in functions

Here are a few simple examples:

1.abs () to find the absolute value

2.all () If all elements of the iterable are true (or if they can be iterated), the returnTrue

3.any () returns if any element of iterable is true True . If iterable is empty, it returnsFalse

4.callable () returns if the object parameter appears adjustable, True otherwiseFalse

5.divmod () takes two (non-plural) digits as parameters and returns a pair of numbers consisting of quotient and remainder when using integer division. For mixed operand types, the rules for binary arithmetic operators apply. For integers, the result is the (a//b,a%b) same. For floating-point numbers, the result is (q,a%b) , where Q is usually math.floor(a/b) , but can be less than 1

The 6.enumerate () parameter must be an iterative object, the function results in an iterator, the output element and the corresponding index value

7.eval () extracts from the string to execute

8.frozenset () Immutable collection, Frozenset () defines the set of non-deleting elements

9.globals () returns a dictionary that represents the current global symbol table. This is always a dictionary of the current module (within a function or method, which is the module that defines it, not the module from which it is called)

10.round () Rounding of parameters

11.sorted () sort without changing the original list

L=[1,2,4,9,-1]print# small to large print# from big to small

12.zip () Zipper function

Creates an iterator that aggregates the elements from each iterator.

Returns an iterator to a tuple where the i-th tuple contains the element I from each parameter sequence or iteration. When the shortest input can be iterated, the iterator stops. It returns an iterator of 1 tuples using a single, iterative parameter. Without parameters, it returns an empty iterator

13.max ()

Returns the largest or the largest of two or more parameters that can be iterated.

If a positional parameter is provided, it should be a iterable. Returns the largest item in the iteration. If two or more positional parameters are provided, the maximum positional parameters are returned.

Max () can specify key (that is, specify the part to compare)

14.map () mapping

Returns an iterator that applies function to each item of iterable , producing the result

l=[1,2,3,4]m=map (Lambda x:x**2, l)print(list (m))        ----->[1, 4, 9, 16]

15.reduce () Merge

 from Import reduceres=0 for in range:    res+ =Iprint(res )

16.filter () filter preserves elements with a Boolean value of True

names=['ALEX_SB','YUANHAO_SB','WUPEIQI_SB','Egon']Print(List (Filter (LambdaName:name.endswith ('_SB'), names))--->['ALEX_SB','YUANHAO_SB','WUPEIQI_SB']

The detailed built-in function introduction can be referred to the following: https://www.rddoc.com/doc/Python-3.6.0/library/functions/

Second, anonymous function (lambda expression)

def func (x):     return x**2print(func (2))Lambda x:x**2        # The upper function can be directly written in this form 

The lambda function comes with a return value

Anonymous functions can only replace some very simple functions, which are used in conjunction with other functions.

Another situation is that some functions are defined after use only once, if not deleted will occupy the memory space, delete will be very troublesome, then you can use the anonymous function

Third, recursion

In the process of invoking a function, the function itself is used directly or indirectly

Recursive efficiency is very low, need to go to the next recursive to retain the current state, Python is not like other languages, no tail recursion, but Python has restrictions, do not allow the user infinite recursion

Characteristics of recursion:

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 layers will cause stack overflow

Example:

#1 The contents of the document are as follows: Name, gender, age, salary##Egon Male#Alex Male 30000#Wupeiqi Female 20000#Yuanhao Female 10000##Requirements:#remove each record from the file into the list,#each element of the list is {' name ': ' Egon ', ' sex ': ' Male ', ' age ': the form of ' salary ': 3000}##2 based on the list obtained by 1, take out the information of the person with the highest salary#3 based on 1 to the list, take out the information of the youngest person#4 based on the list obtained in 1, the name in each person's information is mapped to the first letter capitalized form#5 According to the 1 obtained list, filter out the information of the person whose name begins with a#6 using recursion to print the Fibonacci sequence (first two numbers and get the third number)#0 1 1 2 3 4 7 ...With Open ('B.txt', encoding='Utf-8') as F:l=[{'name': Line.split () [0],'Sex': Line.split () [1],' Age': Line.split () [2],'Salary': Line.split () [3]}              forLineinchF]#2.Print(Max (l,key=Lambdai:i['Salary']))#3.Print(Min (l,key=Lambdai:i[' Age']))#4.M=map (Lambdax:x['name'].capitalize (), L)Print(List (m))#5.Print(List (Filter (LambdaX: not(x['name'].startswith ('a') , L )))#6.deff (n):ifn==0:return0elifN==1:        return1Else:        ifn==1000:            returnF (1000)        Else:            returnF (n-2) +f (n-1) forIinchRange (150):    Print(f (i))

  

Python-based built-in functions and recursion

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.