First, the algorithm is introduced
import time
start_time = time.time()
for a in range(0, 1001):
for b in range(0, 1001):
for c in range(0, 1001):
if a**2 + b**2 == c**2 and a+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!")
a, b, c: 0, 500, 500
a, b, c: 200, 375, 425
a, b, c: 375, 200, 425
a, b, c: 500, 0, 500
elapsed: 214.583347
complete!
依据三个变量之间的关系,减少一个变量,降低维度
import time
start_time = time.time()
for a in range(0, 1001):
for b in range(0, 1001):
c = 1000-a-b
if a**2 + b**2 == c**2:
print("a, b, c:%d, %d, %d" % (a, b, c))
end_time = time.time()
print("times:%d" % (end_time - start_time))
a, b, c:0, 500, 500
a, b, c:200, 375, 425
a, b, c:375, 200, 425
a, b, c:500, 0, 500
times:1
Second, the time complexity
1. Why do we need the complexity of
事后统计法:把代码跑一遍,通过统计、监控,就能得到算法执行的时间和占用的内存大小。
- The test results are very dependent test environment
Test results are affected by large-scale data
needs without a specific test data to test the method on the efficiency of the algorithm can be roughly estimated.2, a large degree of complexity O notation
All code execution time T (n) n is proportional to the frequency of each line of code.
Big O time complexity of a code indicating the execution time with the scale of growth trends in data, also known as asymptotic time complexity, short time complexity.Time complexity analysis
only concerned with the number of cycles up to a code
addition rule: the complexity of the overall complexity equal to the magnitude of the largest part of the code of
the multiplication rule: the complexity of nested code equal to the complexity of the inner and outer nested code3, several common time complexity of the case study
- (1) O
In general, as long as the loop, a recursive algorithm statement does not exist, even if there are thousands of lines of code, the time complexity is O (1). - O (logn), O (nlogn )
when using large tag complexity O, the coefficient can be neglected, i.e. O (Cf (n)) = O (f (n)) O (m + n), O (m * n)
code complexity is determined by the size of two data4, space complexity analysis
Asymptotic space complexity: that the relationship between the growth of storage algorithms and data scale.
5, the time complexity of the possibilities:
Algorithm to complete the work requires a minimum number of basic operations, that is the optimal time complexity of
how much the basic arithmetic operations take up the job done, that is the worst time complexity of
the algorithm to complete the work required average number of basic operations, namely the average time complexity