Python built-in functions and recursion, python built-in Recursion

Source: Internet
Author: User
Tags integer division iterable

Python built-in functions and recursion, python built-in Recursion

I. built-in functions

The following is a brief introduction:

1. abs () calculates the absolute value.

2. all () IfIterableAll elements of are true (or if the iteratable is empty), returnTrue

3. any () IfIterableIf any element of is true, returnTrue. If iterable is null, returnFalse

4. callable () IfObjectIf the parameter is adjustable, returnTrueOtherwise, returnFalse

5. divmod () uses two (non-plural) numbers as parameters and returns a pair of numbers composed of the quotient and remainder when integer division is used. The binary arithmetic operator rules are applicable to mixed operand types. For integers, The result corresponds(a//b,a%b). For floating point numbers, the result is(q,a%b), WhereQUsuallymath.floor(a/b)But can be less than 1

6. The enumerate () parameter must be an iteratable object. The function running result is used to obtain an iterator, the output element and the corresponding index value.

7. eval () extract the string and execute it.

8. frozenset () is an unchangeable set. elements cannot be added or deleted to a set defined by frozenset ().

9. globals () indicates the dictionary of the current global symbol table. This is always the dictionary of the current module (inside a function or method, this is the module that defines it, rather than the module from which it calls it)

10. round () rounds the parameters

11. sorted () sorting without changing the original list

L = [,-1] print (sorted (l) # print from small to large (sorted (l, reverse = True) # from large to small

12. zip () zipper Function

Create an iterator to aggregate elements from each iterator.

Returns the iterator of the tuples.I-Th tuples contain the numberIElements. When the shortest input is exhausted, the iterator stops. Use a single iteratable parameter, which returns the iterator of 1 tuples. No parameter. It returns an empty iterator.

13. max ()

Returns the greatest iterator or two or more parameters that can be iterated.

If a location parameter is provided, it should be an iterable. Returns the iterator In the iteration. If two or more location parameters are provided, the maximum location parameter is returned.

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

14. map () ing

Returns an iterator that appliesFunctionToIterableResults are generated for each project.

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

15. reduce () Merge

from functools import reduceres=0for i in range(100):    res+=iprint(res)

16. filter () filter elements that retain the Boolean value True

names=['alex_sb','yuanhao_sb','wupeiqi_sb','egon']print(list(filter(lambda name:name.endswith('_sb'),names)))--->['alex_sb', 'yuanhao_sb', 'wupeiqi_sb']

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

Ii. Anonymous functions (lambda expressions)

Def func (x): return x ** 2 print (func (2) lambda x: x ** 2 # The above function can be directly written in this form.

Built-in return values of lambda Functions

Anonymous functions can only replace some very simple functions, mainly used with other functions.

Another case is that some functions cannot be used once after definition. If they are not deleted, they will occupy the memory space and will be difficult to delete. In this case, anonymous functions can be used.

Iii. Recursion

When a function is called, the function itself is directly or indirectly used.

The recursion efficiency is very low. The current State needs to be retained when entering the next recursion. Unlike other languages, Python does not have tail recursion. However, Python has restrictions and does not allow infinite recursion.

Recursive features:

1. There must be a clear termination condition

2. Each time you enter a deeper layer of recursion, the problem scale should be reduced compared to the previous recursion.

3. the recursion efficiency is not high. Too many layers of recursion will cause stack overflow.

Example:

#1 the content of the file is as follows: name, gender, age, salary ## egon male 18 3000 # alex male 38 30000 # wupeiqi female 28 20000 # yuanhao female 28 10000 # requirement: # retrieve each record from the file and put it in the list, # Each element in the list is {'name': 'egon', 'sex': 'male', 'age': 18, 'salary ': 3000} form #2 retrieve the information of the person with the highest salary according to the list obtained by 1 #3 according to the list from 1, retrieve the information of the youngest person. #4. Map the names in the information of each person to the first letter in the upper-case form. #5. Obtain the list according to 1, filter out the information of people whose names start with a #6 print the Fibonacci series recursively (the sum of the first two numbers to 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]} \ for line in f] #2. print (max (l, key = lambda I: I ['salary ']) #3. print (min (l, key = lambda I: I ['age']) # 4.m= map (lambda x: x ['name']. capitalize (), l) print (list (m) #5. print (list (filter (lambda x: not (x ['name']. startswith ('A'), l) # 6.def f (n): if n = 0: return 0 elif n = 1: return 1 else: if n = 1000: return f (1000) else: return f (n-2) + f (n-1) for I in range (150): print (f (I ))

 

  

 

Related Article

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.