Algorithm Basics
1, what is the algorithm?
Algorithm (algorithm): A computational process, a method of problem solving
2. Review: Recursion
Two characteristics of recursion:
- Call itself
- End condition
Comparison of two important recursive functions:
# from Big to small def func3 (x): if x > 0: print (x) func3 (x-1) # func3 (5) # 5 4 3 2 # from small to large def func4 (x): if x > 0 : Func4 (x-1) print (x) Func4 (5) # 1 2 3 4 5
3. Complexity of Time
Time complexity: One thing to evaluate the efficiency of an algorithm:
Print (' Hello World ') # 0 (1) for I in Range (n): # O (n) print ("Hello World") for I in Range (n): # O (n^2)
for j in Range (n): print ("Hello World") for I in Range (n): # O (n^3) for J in Range (N): For K in Ran GE (n): print (' Hello world ')
The first one prints a time complexity of O (1), the second prints n times, so the time complexity is O (n), and the 34th one is N2 and N 3 times.
So what is the time complexity in the code below?
# Not O (3) but O (1) print (' Hello World ') print (' Hello Python ') print (' Hello algorithm ') # not O (n2+n) but O (N2) for I in Range (n): Print (' Hello World ') to J in range (n): print (' Hello World ') # not O (1/2n2) but O (N2) for I in Range (n): For J in Ran GE (i): print (' Hello world ')
And look at the following code:
# time Complexity O (log2n) or O (Logn) while n > 1: print (n) n = n//n=64 output: # 64# 32# 16# 8# 4# 2
Summary:
Time complexity is an equation (unit) that is used to estimate the run time of an algorithm.
In general, algorithms with low time complexity are faster than algorithms with low complexity.
Common time complexity (sorted by duration)
- O (1) <o (LOGN) <o (n) <o (Nlogn) <o (n2) <o (N2logn) <o (n3)
Uncommon time complexity (look just fine)
How to judge the complexity of time at a glance?
- The process of halving the cycle? O (LOGN)
- Several loops are the complexity of N's several sides.
4. Complexity of space
Spatial complexity: An equation used to evaluate the size of an algorithm's memory footprint
List Lookup
List lookup: Find the specified element from the list
- Input: list, find element
- Output: element subscript or no element found
1. Sequential Search
Start with the first element of the list and search in order until you find it
2, two-point search
Starting from the candidate area Data[0:n] of the ordered list , the candidate area can be reduced by half by comparing the value of the lookup with the median of the candidate area.
Python development "Chapter 28": Algorithms