python series 4

巴扎黑
Release: 2017-06-23 16:29:47
Original
1574 people have browsed it

Directory

  • Recursive algorithm analysis

  • risk Bubble sorting analysis

  • Decorator analysis

1. Recursion

 1. The definition of recursion

  Recursion, also known as recursion, in mathematics and computer science, refers to the method of using the function itself in the definition of the function. The term recursion is also used longer to describe the process of repeating things in a self-similar way.

F0 = 0F1 = 1
Copy after login

2. The principle of recursion

   (1). Example:

 defth == 5= a1 += defth + 1== recursion(1, 0, 1(ret)
Copy after login

The following picture shows the execution process of the entire function. The red ones represent nesting layer by layer inside, and the green ones represent the return values ​​of the function being returned layer by layer. In fact, recursion is this principle. After entering this function again through the execution flow of a function, after returning a value through a condition, it returns again layer by layer according to the execution flow just now, and finally gets the return value, but when recursing Two points should be noted:

1. His condition must be such that his recursion can return a value within a certain condition, otherwise it will continue to recurse until the computer resources are exhausted (Python has recursion by default Number of times limit)

 2. Return value, the recursive function inside generally needs to give it a certain return value, otherwise you will not get the desired value when the last recursion is returned.

 

2. Bubble sorting

1. Bubble sorting principle

Bubble sorting is a Simple sorting algorithm. He repeatedly walks through the sequence to be sorted, comparing two elements at a time and swapping them if they are in the wrong order.

冒泡排序算法的运作如下:
  1. 比较相邻的元素。如果第一个比第二个大,就交换他们两个。
  2. 对每一对相邻元素作同样的工作,从开始第一对到结尾的最后一对。这步做完后,最后的元素会是最大的数。
  3. 针对所有的元素重复以上的步骤,除了最后一个。
  4. 持续每次对越来越少的元素重复上面的步骤,直到没有任何一对数字需要比较
Copy after login

The principle of exchanging data

Use a peripheral variable to save the original value first, and then exchange data through point-to-address conversion. Note: When temp points to a, and then a points to b, the point of temp itself does not change. As shown in the figure below, a points to b, but temp still points to the address of a, so it is still 66

a = 66b = 88temp = a 
a = b 
b = temp
Copy after login

 

  The principle of bubble sort

 

 2. Bubble sorting Bubble sorting example

 1 # -*- coding:utf-8 -*- 2 # zhou 3 # 2017/6/17 4 list = [0, 88, 99, 33, 22, 11, 1] 5 for j in range(1, len(list)): 6     for i in range(len(list) - j): 7         # 如果第一个数据大, 则交换数据, 否则, 不做改变 8         if list[i] > list[i + 1]: 9             temp = list[i]10             list[i] = list[i + 1]11             list[i + 1] = temp12 print(list)
Copy after login

3. Decorator

 1. Decorator definition

  What is a decorator? Simply put, it is a subtle extension of the code without changing the source function code to further enhance its functionality. A decorator is a function, a function loaded on top of other functions.

Let’s first understand a few concepts:

# From the above, it can be seen that the execution flow of the function should be from top to bottom. That is to say, the code first loads the first test1 into the memory, and then allocates a new memory to store the second test1.

This should be the point where the first test1 has been changed to 890673481792.

def test1():print('日本人.')print(id(test1))def test1():print('中国人.')print(id(test1))
test1()

执行结果:890673481656
890673481792中国人.
Copy after login
  <2>. Function as a variable

    It can be seen from the following results that the function name is actually a variable that can be used to pass variables.

                      <3> . Function nesting   Three functions are defined here, test1, test2, test3, 3 has 1 nested in it, and 1 has 2 nested in it. From its results, you must also see that the function execution flow.

(=<function test1 at 0x000000E2D403C7B8>
<function test1 at 0x000000E2D403C7B8>
Copy after login

  2. 装饰器原理

    (1). 装饰器的写法和使用

      <1>. 装饰器也是一个函数

      <2>. 使用装饰器的格式: 在一个函数前面加上:@装饰器的名字

    (2). 装饰器的原理

      <1>. 把test1函数当做一个变量传入outer中

          func = test1

      <2>. 把装饰器嵌套的一个函数inner赋值给test1

          test1 = inner

      <3>. 当执行test1函数的时候,就等于执行了inner函数,因此在最后的那个test1()命令其实执行的就是inner,因此先输出(你是哪国人)

      <4>. 按照执行流执行到func函数的时候,其实执行的就是原来的test1函数,因此接着输出(我是中国人),并把它的返回值返回给了ret

      <5>. 当原来的test1函数执行完了之后,继续执行inner里面的命令,因此输出了(Oh,hh, I love China.)

    (3). 装饰器的总结

      由上面的执行流可以看出来,其实装饰器把之前的函数当做参数传递进去,然后创建了另一个函数用来在原来的函数之前或者之后加上所需要的功能。

(=((
Copy after login

 

  3. 带参数的装饰器

    为了装饰器的高可用,一般都会采用下面的方式,也就是无论所用的函数是多少个参数,这个装饰器都可以使用

    Python内部会自动的分配他的参数。

# -*- coding:utf-8 -*-# zhou# 2017/6/17def outer(func):def inner(a, *args, **kwargs):print('你是哪国人?')
        ret = func(a, *args, **kwargs)print('Oh, hh, I love China.')return inner

@outerdef test1(a, *args, **kwargs):print('我是中国人.')

test1(1)
Copy after login

  3.  装饰器的嵌套

   <1>. 第一层装饰器的简化(outer装饰器)

    

    

    <2>. 第二层装饰器简化(outer0装饰器)

    

    <3>. 装饰器嵌套攻击额,我们可以发现一层装饰器其实就是把原函数嵌套进另一个函数中间,因此我们只需要一层一层的剥开嵌套就可以了。

# -*- coding:utf-8 -*-# zhou# 2017/6/17def outer0(func):def inner():print('Hello, Kitty.')
        ret = func()print('我是日本人.')return innerdef outer(func):def inner():print('你是哪国人?')
        ret = func()print('你呢?')return inner
@outer0
@outerdef test1():print('我是中国人.')

test1()

结果Hello, Kitty.
你是哪国人?
我是中国人.
你呢?
我是日本人.
Copy after login

 

 

  

 

The above is the detailed content of python series 4. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!