Home Backend Development Python Tutorial Detailed explanation of built-in functions and recursion in Python basics

Detailed explanation of built-in functions and recursion in Python basics

Jun 21, 2017 pm 01:18 PM
python built-in function Base recursion

1. Built-in functions

The following are briefly introduced:

1.abs() Find the absolute value

2. all() If all elements of iterable are true (or if the iterable is empty), returns <span class="pre">True</span>

3.any () If any element of iterable is true, returns <span class="pre">True</span>. If iterable is empty, return <span class="pre">False</span>

4.callable() If the object parameter appears adjustable, return <span class="pre">True</span>, otherwise return <span class="pre">False</span>

##5.divmod() with two takes as arguments a (non-complex) number and returns a pair of numbers consisting of the quotient and remainder when using integer division. For mixed operand types, the rules for binary arithmetic operators apply. For integers, the result is the same as (a<span class="pre">//<span class="pre">b,<span class="pre">a<span class="pre">%<span class="pre">b)<span class="pre"></span></span></span></span></span></span> same. For floating point numbers, the result is (q,<span class="pre">a<span class="pre">%<span class="pre">b)<span class="pre"></span></span></span></span>, where q Usually math.floor(a<span class="pre">/<span class="pre">b)<span class="pre"></span></span></span>, but can be less than 1

6.enumerate() parameters must be iterable objects. The function results in an iterator, which outputs elements and corresponding index values.

7.eval() Extract and execute

8.frozenset() immutable collection, the collection defined by frozenset() cannot add or delete elements

9.globals() Returns a dictionary representing the current global symbol table. This is always a dictionary of the current module (inside a function or method, this is the module in which it is defined, not the module it is called from)

10.round() on the arguments Rounding

11.sorted() Sort without changing the original list

l=[1,2,4,9,-1]print(sorted(l)) #从小到大print(sorted(l,reverse=True)) #从大到小
Copy after login

12.zip() Zipper function

Create an iterator that aggregates elements from each iterator.

Returns an iterator of tuples, where the

i-th tuple contains the ith element from each argument sequence or iteration. The iterator stops when the shortest input iterable is exhausted. Taking a single iterable argument, it returns an iterator of 1-tuples. With no arguments, it returns an empty iterator

13.max()

Returns the maximum item of the iterable or the largest of two or more arguments.

If a positional argument is provided, it should be an iterable. Returns the largest item in the iteration. If two or more positional arguments are supplied, the largest positional argument is returned.

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

14.map() mapping

Returns an iterator, which applies

function Each item to iterable produces the result

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

15.reduce() merge

from functools import reduce

res=0for i in range(100):
    res+=iprint(res)
Copy after login
16.filter() filters and retains elements whose Boolean value is True

names=['alex_sb','yuanhao_sb','wupeiqi_sb','egon']print(list(filter(lambda name:name.endswith('_sb'),names)))--->['alex_sb', 'yuanhao_sb', 'wupeiqi_sb']
Copy after login
For detailed introduction of built-in functions, please refer to the following:

2. Anonymous Function (lambda expression)

def func(x):return x**2print(func(2))lambda x:x**2        #上边的函数就可以直接写成这种形式
Copy after login
lambda function has its own return value

Anonymous functions can only replace some very simple functions and are mainly used in conjunction with other functions

Another situation is that some functions are used only once after being defined. If they are not deleted, they will occupy memory space, and deletion will be very troublesome. In this case, anonymous functions can be used

3. Recursion

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

The recursion efficiency is very low, and the current state needs to be retained when entering the next recursion. Python is not like other Language, there is no tail recursion, but Python has restrictions and does not allow users to recurse infinitely

Characteristics of recursion:

1. There must be a clear end condition

2 .Every time you enter a deeper level of recursion, the problem size should be reduced compared to the last recursion

3. Recursion efficiency is not high, and too many recursion levels will cause stack overflow

Example:

# 1 文件内容如下,标题为:姓名,性别,年纪,薪资#
# egon male 18 3000# alex male 38 30000# wupeiqi female 28 20000# yuanhao female 28 10000#
# 要求:# 从文件中取出每一条记录放入列表中,# 列表的每个元素都是{'name':'egon','sex':'male','age':18,'salary':3000}的形式#
# 2 根据1得到的列表,取出薪资最高的人的信息# 3 根据1到的列表,取出最年轻的人的信息# 4 根据1得到的列表,将每个人的信息中的名字映射成首字母大写的形式# 5 根据1得到的列表,过滤掉名字以a开头的人的信息# 6 使用递归打印斐波那契数列(前两个数的和得到第三个数)#     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 0elif n==1:return 1else:if n==1000:return f(1000)else:return f(n-2)+f(n-1)for i in range(150):print(f(i))
Copy after login

The above is the detailed content of Detailed explanation of built-in functions and recursion in Python basics. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1662
14
PHP Tutorial
1262
29
C# Tutorial
1235
24
PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

How to run sublime code python How to run sublime code python Apr 16, 2025 am 08:48 AM

To run Python code in Sublime Text, you need to install the Python plug-in first, then create a .py file and write the code, and finally press Ctrl B to run the code, and the output will be displayed in the console.

Where to write code in vscode Where to write code in vscode Apr 15, 2025 pm 09:54 PM

Writing code in Visual Studio Code (VSCode) is simple and easy to use. Just install VSCode, create a project, select a language, create a file, write code, save and run it. The advantages of VSCode include cross-platform, free and open source, powerful features, rich extensions, and lightweight and fast.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

How to run python with notepad How to run python with notepad Apr 16, 2025 pm 07:33 PM

Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".

See all articles