1、quicksort算法
列表推导:x^2 for x in list if … : 如果…list每个符合要求的值变成x^2
def quicksort(arr):
if len(arr) <= 1:
return arr
pivot = arr[int(len(arr) / 2)]
left = [x for x in arr if x < pivot]
middle = [x for x in arr if x == pivot]
right = [x for x in arr if x > pivot]
return quicksort(left) + middle + quicksort(right)
arr = [3,6,8,10,1,2,1]
a = quicksort(arr)
2、计时器
import time
class Timer: #@save
"""记录多次运行时间"""
def __init__(self):
self.times = []
self.start()
def start(self):
"""启动计时器"""
self.tik = time.time()
def stop(self):
"""停止计时器并将时间记录在列表中"""
self.times.append(time.time() - self.tik)
return self.times[-1]
def avg(self):
"""返回平均时间"""
return sum(self.times) / len(self.times)
def sum(self):
"""返回时间总和"""
return sum(self.times)
def cumsum(self):
"""返回累计时间"""
return np.array(self.times).cumsum().tolist()
timer = Timer()
f'{timer.stop():.5f} sec'
3、绘图
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(0, 3 * np.pi, 0.1)
y_sin = np.sin(x)
y_cos = np.cos(x)
plt.plot(x, y_sin)
plt.plot(x, y_cos)
plt.plot(x, 2 * x - 3, ls="-", lw=2, label=("2 * x - 3"))
plt.legend()
plt.xlabel('x axis label')
plt.title('Sine and Cosine')
plt.legend(['Sine', 'Cosine'])
plt.show()