Python expands 3 algorithms and data structures

Source: Internet
Author: User

Knowledge Content:

1. Recursive review

2. Common algorithms

3. Commonly used data structures

4.python Cookbook algorithm and data structure collation

Resources:

Http://python3-cookbook.readthedocs.io/zh_CN/latest/index.html

Http://www.cnblogs.com/alex3714/articles/5474411.html

First, recursive review

1. What is recursion: The function internally calls itself

2. Characteristics of recursion

    • Must have a definite end condition
    • Each time you enter a deeper level of recursion, the problem size should be reduced compared to the last recursion
    • Recursive efficiency is not high, too many recursion levels will cause stack overflow

3. Look at the function to say the result

1 deffunc1 (x):2     Print(x)3Func1 (x-1)4Func1 (5)5 #Print to limit count (No exit)6 7 defFunc2 (x):8     ifX >0:9         Print(x)TenFunc2 (x+1) OneFUNC2 (5) A #Print to limit count (No exit) -  - deffunc3 (x): the     ifX >0: -         Print(x) -FUNC3 (x-1) -FUNC3 (5)  + #printed from 5 to 1 -  + defFunc4 (x): A     ifX >0: atFunc4 (x-1) -         Print(x) -FUNC4 (5) - #printed from 1 to 5

4. Classic recursion

(1) Hanoi tower problem

Solution Ideas:

Suppose there are n plates:

    • 1. Move the n-1 disc from A through C to B
    • 2. Move the nth disc from A to C
    • 3. Move the n-1 small disc from B through A to C

1:

2:

3:

Code:

1 defHanoi (A, B, C, n):2     ifn = = 1:3         PrintA" -"C#Move the n-1 plate from A through C to B .4     Else:5Hanoi (A, C, B, n-1)#move the remaining last plate from a to C6         PrintA" -", c)7Hanoi (b, A, C, n-1)#Move the n-1 plate from B through a to C .8 9 TenHanoi'Pillar a','Pillar B','Pillar C', 4)

Summary: Hanoi of the number of moves: H (x) =2h (x-1) +1

(2) Reverse string output

1 defRVs (s):2     ifs = ="":3         returns4     Else:5         returnRVs (s[1:]) +S[0]6 7 8s = RVs ("Hello, Python")9 Print(s)

5. Tail recursion

Second, commonly used algorithms

1. What is an algorithm

Algorithm is a computational process, the method of solving the problem

The algorithm (algorithm) is an accurate and complete description of the solution, a series of clear instructions to solve the problem, and the algorithm represents a systematic method to describe the strategy of solving the problem. In other words, the input of a certain specification can be obtained in a limited time with the required output. If an algorithm is defective, or is not suitable for a problem, executing the algorithm will not solve the problem. Different algorithms may use different time, space, or efficiency to accomplish the same task. The merits and demerits of an algorithm can be measured by the complexity of space and time.

An algorithm should have the following seven important characteristics:

    • poor (finiteness): The poor nature of the algorithm means that the algorithm must be able to terminate after a finite number of steps have been performed
    • exact Sex (definiteness): Each step of the algorithm must have an exact definition
    • Input Items (input): An algorithm has 0 or more inputs to characterize the initial situation of the operand, so-called 0 input refers to the algorithm itself to set the initial conditions
    • Output Items (output): An algorithm has one or more outputs to reflect the result of processing the input data. The algorithm without output is meaningless.
    • Feasibility (effectiveness): Any calculation step performed in the algorithm can be decomposed into basic executable steps, that is, each calculation step can be completed in a limited time (also known as validity)
    • High efficiency of (High efficiency): Fast execution speed and low resource consumption
    • Robustness (robustness): Correct response to data

2. Complexity of time and space

(1) Complexity of time

1 Print("Hello, World")2 3  forIinchrange (n):4     Print("Hello, World")5 6  forIinchrange (n):7      forJinchrange (n):8         Print("Hello, World")9 Ten  forIinchrange (n): One      forJinchrange (n): A          forKinchrange (n): -             Print("Hello, World")

Q. Who is the shortest time to run the above code? What is the method for extracting the current code (algorithm) running speed? The answer is to measure it in terms of time complexity.

time complexity of common algorithms (from small to large): o (1) o (logn) o (n) o (nlogn) o (n^2) o (n^2logn) O (n^3)

Instance:

1 Print('Hello World')2 Print('Hello python')#O (1) Large o, which can be considered to mean "order of" (approximately)3 4N= 645  whileN>1:6     Print(n)#O (LOGN) # n=64 is output in order: 8 4 27n = N//28 9  forIinchrange (n):Ten     Print(i)#O (n) One  A  forIinchrange (n): -      forJinchrange (n): -         Print('Hello World')#O (n^2) the  -  forIinchrange (n): -      forJinchrange (n): -          forKinchrange (n): +             Print('Hello World')#O (n^3)

Note: The complexity of the slice is O (n), because the cut is assigned

Summarize:

    • Time complexity is an equation (unit) used to estimate the run time of an algorithm.
    • In general, algorithms with high time complexity are slower than algorithms with low time complexity
    • The process of halving the cycle is O (Logn), and several loops are the complexity of N's several sides.

(2) Complexity of space

Spatial complexity is a formula used to evaluate the size of the algorithm's memory footprint, with common spatial complexity: O (1) o (n) O (n^2)

Space change Time: The computer resources are sufficient, can use the space consumption to exchange for a certain time

3. Common Search

(1) List lookup

List lookup: Find the specified element from the list

Input: list, element to find, output: element subscript or no element found

List Lookup methods: Sequential lookup and Binary lookup

    • Sequential lookups: Starting with the first element of the list, searching in order until it is found
    • Binary lookup: Searches from subsequent areas of an ordered list by comparing the values found with the median of the candidate area to halve the candidate area

The code for both of these lookups is as follows:

#Sequential Lookup time complex O (n)defLinear_search (Find, data_list): forIinchRange (len (data_list)):ifData_list[i] = =Find:returnIreturn-1#Two-point lookup time complex O (LOGN)defBinary_search (Find, Data_list): Low=0 High=Len (data_list) whileLow <=High:mid= (low + high)//2#Locate Find        ifData_list[mid] = =Find:returnMid#find on the left half        elifData_list[mid] >Find:high= Mid-1#find on the right half        Else: Low= Mid + 1#find returned-1 not found    return-1

(2) Search Practice

There is now a list of learner information, arranged by ID, in the following format:

1 [2{"ID": 1001,"name":"Zhang San"," Age": 20},3{"ID": 1002,"name":"Woz"," Age": 22},4{"ID": 1003,"name":"Alex"," Age": 23},5{"ID": 1004,"name":"HF"," Age": 26},6{"ID": 1005,"name":"KK"," Age": 27},7]

Now it is required to change the binary lookup code, enter the student ID, output the student's subscript below the list and output the complete student information.

The implementation code is as follows:

4. Common sort

The usual sorts are as follows:

Third, the commonly used data structure

Iv. Python Cookbook algorithm and data structure collation

Python expands 3 algorithms and data structures

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.