python-function-day4

Source: Internet
Author: User

1. function 1.1, set

Main functions:

Go to heavy relationship test, intersection \ difference set \ set \ Inverse (symmetric) difference Set a = {1,2,3,4}b ={3,4,5,6}a{1,2,3, 4} Type (a) <class  ' Set ' >a.symmetric_difference (b) {1, 2, 5, 6}b.symmetric_difference (a) {1, 2, 5, 6}a.difference (b) {1, 2} a.union (b) {1, 2, 3, 4, 5, 6}a.issua.issubset (A.issuperset (A.issubset (b) False         
2. Tuples

Read-only list, only count, index 2 methods

Role: If some data do not want to be modified, can save Narimoto group, such as identity card list

3. Dictionaries

Key-value to

特性:无顺序去重查询速度快,比列表快多了比list占用内存多

Why would queries be faster? Because he is a hash type, what is a hash?

The hashing algorithm maps a binary value of any length to a shorter fixed-length binary value, a small binary value called a hash value. A hash value is a unique and extremely compact numeric representation of a piece of data. If you hash a clear text and even change only one letter of the paragraph, subsequent hashes will produce different values. To find two different inputs that hash the same value, it is not possible to compute, so the hash value of the data can verify the integrity of the data. Typically used for quick find and encryption algorithms

Dict will turn all the keys into a hash table and then sort the table so that when you look up a key in the data dictionary by Data[key, Python will first hash the key into a number and then take the number to the hash table without that number. If so, get the index of this key in the hash table and get the index to the memory address of the value corresponding to this key.

It still doesn't answer that. Finding a data is faster than a list, right? Hehe, I'll announce it in class.

4. Character encoding

First, Python2.

py2里默认编码是ascii文件开头那个编码声明是告诉解释这个代码的程序 以什么编码格式 把这段代码读入到内存,因为到了内存里,这段代码其实是以bytes二进制格式存的,不过即使是2进制流,也可以按不同的编码格式转成2进制流,你懂么?如果在文件头声明了#_*_coding:utf-8*_,就可以写中文了, 不声明的话,python在处理这段代码时按ascii,显然会出错, 加了这个声明后,里面的代码就全是utf-8格式了在有#_*_coding:utf-8*_的情况下,你在声明变量如果写成name=u"大保健",那这个字符就是unicode格式,不加这个u,那你声明的字符串就是utf-8格式utf-8 to gbk怎么转,utf8先decode成unicode,再encode成gbk

Besides, Python3.

The default file encoding in Py3 is UTF.-8, so you can write the Chinese directly, do not need the file header declaration code, dry Beautiful You declare the variable by default isUnicode encoding, not UTF-8, because the default isunicode (unlike in Py2, you want to directly declare unicode also have to add a u in front of the variable), when you want to turn into GBK, Direct Your_str.encode ( "GBK") is available but py3 when you are in Your_str.encode ( "GBK") , the feeling seems to add an action, that is, encode data into the bytes, I, this is how a situation, because in Py3, str and bytes made a clear distinction, You can understand that bytes is 2 into the flow, you would say, I see not 010101 such 2, that's because Python gives you the ability to manipulate the data at the level of memory to help you to do a layer of encapsulation, otherwise you will see a bunch of 2 the system, Can you see which character corresponds to which paragraph of 2 the binary? What the?  Your own conversion, come on, you even more than  2 digits of the number plus and minus operations are laborious, or save worry bar. Then you say, in the py2 there seems to be bytes ah, yes, but py2 bytes only to str made an alias, not like Py3 to show you more than a layer of encapsulation, but in fact, its interior is encapsulated. So to speak, whether it is 2 or three, from hard disk to memory, the data format is  101,012 into-->b \xe4\xbd\xa0\xe5\xa5\xbd ' bytes Type--and follow the specified encoding to the text you can read       

Coding applications more than the scene should be a reptile, the internet, many websites with a very miscellaneous encoding format, although the overall trend has become utf-8, but now still very miscellaneous, so crawling Web pages need you to do a variety of code conversion, but life is becoming better, looking forward to a world without transcoding.

Finally, encode is a piece of fucking shit, Noboby likes it.

String converted to Unicode directly before the string plus u example msg = u ' Hello '

在python3中   变量默认 是Unicode编码格式  只有unicode有encode方法
2. Functions

In basic it is called subroutine (sub-process or subroutine), in Pascal is called procedure (process) and function, in C only function, in Java is called method.

2.1. # # #函数定义

Definition: A function that encapsulates a set of statements by a name (function name), and to execute the function, simply call the name of its functions

2.2. Function Characteristics:
减少重复代码使程序变的可扩展使程序变得易维护

Syntax definitions

Def sayhi (): #函数名
Print ("Hello, I ' m nobody!")

Sayhi () #调用函数

2.3, function parameters and local variables 2.3.1, formal parameters

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.3.2, actual parameters

Arguments can be constants, variables, expressions, functions, and so on, regardless of the type of argument, and when a function call is made, 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

The default is the defined variable after assigning the default parameter to the variable

2.4. Return value:
    1. Once your function has been called and executed, then the program outside of your function, there is a way to control the function of the execution process, the external program can only quietly wait for the execution of the function results, why wait for the function results, to the external program according to the function of the results to determine the next step to go, The result of this execution is returned to the external program in the form of return
    2. Return represents the end of a function
    3. Return can be returned with any data type
    4. For the user angle, the function can return any number of values, but for the PY itself, the function can return only one value
2.5. Key parameters

Under normal circumstances, to pass parameters to the function in order, do not want to order the key parameters can be used, just specify the parameter name, but remember a requirement is that the key parameters must be placed after the position parameter.
1

Stu_register (age=22,name= ' Alex ', course= "Python",)

  

2.6, non-fixed parameters 2.6.1, *args

If your function is not sure how many parameters the user wants to pass in the definition, you can use the non-fixed parameter

def stu_register(name,age,*args): # *args 会把多传入的参数变成一个元组形式 print(name,age,args) stu_register("stone",22)#输出#Alex 22 () #后面这个()就是args,只是因为没传值,所以为空 stu_register("Jack",32,"CN","Python")#输出# Jack 32 (‘CN‘, ‘Python‘)
2.6.2, can also have a **kwargs
def stu_register(name,age,*args,**kwargs): # *kwargs 会把多传入的参数变成一个dict形式 print(name,age,args,kwargs) stu_register("stone",22)#输出#stone 22 () {}#后面这个{}就是kwargs,只是因为没传值,所以为空 stu_register("liang",23,"CN","Python",sex="male",province="hebei")#输出# liang 23 (‘CN‘, ‘Python‘) {‘province‘: ‘hebei‘, ‘sex‘: ‘male‘}
2.7. Local variables and global variables

Local variables: Valid only within the current function
Global variables: Variables that can be used throughout the program, usually at the beginning of a file

Local changes to global variables: local need to declare global login_status and then change

2.7.1, local variables
name = "stone" def change_name(name):    print("before change:",name) name = "hello" print("after change", name) change_name(name)print("在外面看看name改了么?",name)输出 before change: stoneafter change: hello在外面看看name改了么? stone
Summary of 2.7.2, global and local variables:

A variable defined in a subroutine is called a local variable, and a variable defined at the beginning of the program is called a global variable.
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 in sub-programs that define local variables, and global variables work elsewhere.

3. Recursion

Inside a function, you can call other functions. If a function calls itself internally, the function is a recursive function.

def calc(n):    print(n)    if int(n/2) ==0: return n return calc(int(n/2)) calc(10)

Output:
10
5
2
1

3.1, recursive characteristics:
    1. Must have a definite end condition

    2. Each time you enter a deeper level of recursion, the problem size should be reduced compared to the last 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, whenever entering a function call, the stack will add a stack of frames, whenever the function returns, the stack will be reduced by a stack of frames. Because the size of the stack is not infinite, there are too many recursive calls, which can cause the stack to overflow.

3.2. Anonymous function:

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

#这段代码def calc(n): return n**nprint(calc(10)) #换成匿名函数calc = lambda n:n**nprint(calc(10))

Anonymous functions are mainly used in conjunction with other functions, as follows

map(lambda x:x**2,[1,5,7,4,8])for i in res: print(i)输出125491664map()把后面的值给前面的函数 处理 结果输出lambda
3.3, high-order function:

Pass a function as an argument to another function
A variable can point to a function, which can receive a variable, and a function can receive another function as a parameter, a function called a higher order function.

def add(x,y,f):    return f(x) + f(y) res = add(3,-6,abs)print(res)
3.4. Introduction to Functional programming

Programming paradigm-oriented process for solving problems, using functions to compare multiple

function is a kind of encapsulation supported by Python, we can decompose complex tasks into simple tasks by splitting large pieces of code into functions through a layer of function calls, which can be called process-oriented programming. function is the basic unit of process-oriented program design.

Functions in functional programming the term does not refer to a function in a computer (actually a subroutine), but rather to a function in mathematics, the mapping of an independent variable. This means that the value of a function is determined only by the value of the function parameter, not by other states. For example, the sqrt (x) function calculates the square root of X, as long as x is not changed, and whenever the call is called, the value is constant.

Python provides partial support for functional programming. Because Python allows the use of variables, Python is not a purely functional programming language.

First, the definition

Simply put, "functional programming" is a "programming paradigm" (programming paradigm), which is how to write a program's methodology.

The main idea is to write the operation process as much as possible into a series of nested function calls. For example, there is now a mathematical expression:

  (1 + 2) * 3 - 4

Traditional procedural programming, which may be written like this:

  var a = 1 + 2;  var b = a * 3;  var c = b - 4;

Functional programming requires the use of functions, which can be defined as different functions, and then written as follows:

  var result = subtract(multiply(add(1,2), 3), 4);

This code evolves the following and can be turned into this

add(1,2).multiply(3).subtract(4)

This is basically the expression of natural language. Look at the following code, you should be able to understand its meaning at a glance:

merge([1,2],[3,4]).sort().search("2")

As a result, the code for functional programming is easier to understand.

To learn functional programming, do not play py, play Erlang,haskell, well, I will only so much ...

4. Built-in function method

#compile# f = open("函数递归.py")# data =compile(f.read(),‘‘,‘exec‘)# exec(data)#printmsg = "又回到最初的起点"f = open("tofile","w")print(msg,"记忆中你青涩的脸",sep="|",end="",file=f)#slicea = range(20)pattern = slice(3,8,2)for i in a[pattern]: #等于a[3:8:2] print(i)几个内置方法用法提醒
4.1 All () the contents of the list are true and only 0 is false
all()>>> a = [1,2,3]>>> all(a)True>>> a = [0,2,3]>>> all(a)False>>>
4.2, judging the list of one of the true is True
any()列表中有一个为真 就为真 列表为空 就为假
4.3, print ("place") in the form of ASCII code 4.4, bin () converts a number to binary form represents 4.5, bytes () b= b ' ABC ' 4.6, callable () determine if the function is available 4.7, To view the corresponding ASCII correspondence for the corresponding character
print(chr(98))print(old(‘b‘))
4.8, compile ()
相当于import 来导入引用
4.9.

Eval () EXEC ()
Eval () operation

4.10, Complex () Enter a numeric output plural format 4.11, dir (): Return function Method 4.12, print (Divmod (10,2)): Return quotient and remainder 4.13, filter: filters () = = Map ()
filter(lambda x:x>5,range(10)):过滤
4.14. Frozenset ({1,2,3,4,5,5}) turns a collection into read-only 4.15, and print (Globals ()) prints all the spatial data that is open in the current program's memory in the form of a dictionary. 4.16. Print (local ()) local () prints only local 4.17, binary
print(hex(8))0x80x代表的16进行
4.18, Max () the maximum value in the current list 4.19, min () the minimum value of the current list 4.20, print (POW (4,9))
幂运算4的9次方
4.21. Printing print ()
"又回到最初的起点"f = open("tofile","w")print(msg,"记忆中你青涩的脸",sep="|",end="",file=f)
4.22, reversed () List: Invert

More for the reversal of strings, there is no reversal method for strings:

4.23, print (Round (10.23,1)) five six into 4.24, convert the list to set set ()
data = [1,2,5,6,7,7]set(data)
4.25, sort sorted4.26, Sum sum () The sum of the list 4.27, VARs () print all addresses of the current program 4.28, zip () zipper
a= [1,3,5,7]b = [2,4,6,8]for i in zip(a,b): print(i)拉链,按照最小的来合并

python-function-day4

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.