Algorithm is the essence of computer processing information, because the computer program is essentially an algorithm to tell the computer the exact steps to perform a specified task. Generally, when the algorithm processes the information, it reads the data from the storage address of the input device or data, writes the result to the output device or to a storage address for later invocation.
Algorithm is an independent existence of a problem-solving methods and ideas.
How to find all possible combinations of a, B and C if a+b+c=1000 is introduced and a^2+b^2=c^2 (A,b,c is the natural number)?
Solution 1:
ImportTimestart_time=time.time ()#attention is a triple loop forAinchRange (0, 1001): forBinchRange (0, 1001): forCinchRange (0, 1001): ifa**2 + b**2 = = C**2 andA+b+c = = 1000: Print("A, B, C:%d,%d,%d"%(A, B, c)) End_time=time.time ()Print("Elapsed:%f"% (End_time-start_time))Print("complete!")#############################operating results: A, B, c:0,500, 500A, B, C:200, 375, 425A, B, C:375, 200, 425A, B, C:500, 0, 500Elapsed:214.583347complete!Enumeration Method
The five main features of the algorithm:
1. Input: The algorithm has 0 or more inputs;
2. Output: The algorithm has a minimum of 1 or more outputs;
3. Poor: The algorithm will automatically end after a limited number of steps without an infinite loop, and each step can be completed within an acceptable time;
4. Certainty: Each step of the algorithm has a definite meaning and does not appear two semantics;
5. Feasibility: Each step of the algorithm is feasible, that is, each step can perform a limited number of times to complete.
According to the above enumeration method, it can be seen that multilayer nested for loops are very time consuming, similar to the growth of Cartesian product. We can completely remove the C loop, according to A + b+c=1000,c=1000-a-B.
Our code can be changed to:
ImportTimestart_time=time.time ()#attention is a double loop . forAinchRange (0, 1001): forBinchRange (0, 1001-a): C= 1000-a-bifa**2 + b**2 = = C**2: Print("A, B, C:%d,%d,%d"%(A, B, c)) End_time=time.time ()Print("Elapsed:%f"% (End_time-start_time))Print("complete!")###########################operating results: A, B, c:0,500, 500A, B, C:200, 375, 425A, B, C:375, 200, 425A, B, C:500, 0, 500Elapsed:0.182897complete!Modify Code
The second approach is obviously much more efficient in terms of run time. We use the big O method to determine the efficiency of the algorithm.
We assume that the computer executes the algorithm every basic operation time is a fixed time unit, then how many basic operations represent how much time units will be spent. However, for different machine environments, the exact unit time is different, but how many basic operations (that is, how much time units are spent) are the same in the scale order, thus ignoring the impact of the machine environment and the time efficiency of the objective response algorithm.
How to explain the Big O method: "Big O notation": For monotone integer function f, if there is an integer function g and a real constant c>0, so that for a sufficiently large n always have f (n) <=c*g (n), it is said that the function g is an asymptotic function of f (ignoring the constant), recorded as f (n) =o (g ( In other words, the growth rate of function f is constrained by the function g in the limit meaning of infinite, that is, function f is similar to function G.
Time complexity: Assuming the existence of the function g, so that the algorithm A to deal with the size of an example of the problem of n time is t (n) =o (g (n)), then called O (g (n)) is the asymptotic time complexity of algorithm A, referred to as the time complexity, is recorded as T (N).
In short, the Big O method is to ignore the constant C, it is believed that 3*n**2 and 100*n**2 belong to the same magnitude, if the cost of the two algorithm to deal with the same size of the two functions, respectively, they think their efficiency "almost", are n**2 level.
Several basic calculation rules of time complexity,
The basic operation, that is, only the constant term, that its time complexity is O (1),
Sequential structure, the complexity of time is calculated by addition,
Loop structure, time complexity is calculated by multiplication,
Branching structure, time complexity takes maximum value,
When judging the efficiency of an algorithm, it is often only necessary to pay attention to the highest number of operations, other minor items and constant items can be ignored,
In the absence of special instructions, the time complexity of the algorithm we are analyzing refers to the worst-case complexity of time.
Back to our initial question, we used the enumeration method for the first time complexity:
T (n) = O (n*n*n) = O (n**3)
The second time complexity of the algorithm:
T (n) = O (n*n* (+)) = O (n*n) = O (n**2)
The algorithm diagram we wrote earlier also explains the Big O method:
The time-consuming order of the large O-method is from small to large: O (1) < O (Logn) < O (n) < O (Nlogn) < O (N2) < O (n3) < O (2n) < O (n!) < O (NN).
Timeit Module
The Timeit module can be used to test the execution speed of a small piece of Python code.
class Timeit. Timer (stmt='pass', setup='pass', Timer=<timer function >) A timer is a class that measures the speed of a small piece of code execution. The stmt parameter is the code statement (statment) to be tested, and the setup parameter is the setting required to run the code; The timer parameter is a timer function, which is related to the platform. Timeit. Timer.timeit (number =1000000) The object method in the timer class that tests the execution speed of the statement. The number parameter is the test count when the code is tested, which defaults to 1 million times. method returns the average time spent executing code, and the number of seconds for a float type.
Timeit Module
deftest1 (): L= [] forIinchRange (1000): L= L +[i]deftest2 (): L= [] forIinchRange (1000): L.append (i)deftest3 (): L= [I forIinchRange (1000)]deftest4 (): L= List (range (1000)) fromTimeitImportTimert1= Timer ("test1 ()","From __main__ import test1")Print("concat", T1.timeit (number=1000),"seconds") T2= Timer ("test2 ()","From __main__ import test2")Print("Append", T2.timeit (number=1000),"seconds") T3= Timer ("test3 ()","From __main__ import test3")Print("Comprehension", T3.timeit (number=1000),"seconds") T4= Timer ("test4 ()","From __main__ import test4")Print("List Range", T4.timeit (number=1000),"seconds")#(' concat ', 1.7890608310699463, ' seconds ')#(' Append ', 0.13796091079711914, ' seconds ')#(' comprehension ', 0.05671119689941406, ' seconds ')#(' list range ', 0.014147043228149414, ' seconds ')efficiency of generating lists
So don't write anything in the future.l = l + [i]增加列表了(每次都生成新列表而+=则不会生成新列表+=与extend效果一样),因为列表本身的结构类型所以在列表的头部或者尾部增加或删除也是有区别的。
x = Range (2000000) Pop_zero= Timer ("x.pop (0)","From __main__ import x")Print("Pop_zero", Pop_zero.timeit (number=1000),"seconds") x= Range (2000000) Pop_end= Timer ("X.pop ()","From __main__ import x")Print("Pop_end", Pop_end.timeit (number=1000),"seconds")#(' Pop_zero ', 1.9101738929748535, ' seconds ')#(' Pop_end ', 0.00023603439331054688, ' seconds ')differences between insert and delete before and after a list
We want the algorithm to solve the problem the faster the better, so we need to consider how the data exactly how to save the problem, this is data structure. Lists and dictionaries are two of the data structures that Python built to encapsulate for us.
Data is an abstract concept that is categorized into basic types in the programming language. such as: Int,float,char and so on. Data elements are not independent, there are specific relationships, and these relationships are structures. The data structure index is the relationship between the elements in the object.
An abstract data type (ADT) is a bundle of data types and operations on a data type for encapsulation. The purpose of introducing abstract data types is to separate the representations of data types and the implementation of operations on data types from the references to these data types and operations in the program. Similar to object-oriented provider API operations.
The Timeit module of a little algorithm (one) per day