1、求出2-10000内的所有素数
Python:
t = time() p_list = [] for i in range(2, b): flag = True for p in p_list: if p > math.sqrt(i): break if i % p == 0: flag = False break if flag: p_list.append(i) print(time() - t) print(p_list)
把素数判断部分封装为函数:
def is_prime3(x): flag = True for p in p_list2: if p > math.sqrt(x): break if x % p == 0: flag = False break if flag: p_list2.append(x) return flag p_list2 = [] t = time() list(filter(is_prime3, list(range(2, b)))) print(time() - t) print(p_list2)
- 判断到sqrt(x)的素数即可,而不用判断所有数
2、环形公路堵车模拟
路上有N辆车,以不同速度行驶
1)某辆车当前速度是v
2)若前方可见范围内无车,则下一秒车速提高到v+1,直到最高限速
3)若前方有车,车距为d,且d<v,则下一秒车速将为d-1
4)每辆车以概率p随机减速v-1
Python:
1 import numpy as np 2 import matplotlib as mpl 3 import matplotlib.pyplot as plt 4 5 6 def clip(x, path): 7 for i in range(len(x)): 8 if x[i] >= path: 9 x[i] %= path 10 11 12 if __name__ == "__main__": 13 mpl.rcParams['font.sans-serif'] = ['SimHei'] #中文字体 14 mpl.rcParams['axes.unicode_minus'] = False 15 16 path = 5000 # 环形公路的长度 17 n = 100 # 公路中的车辆数目 18 v0 = 50 # 车辆的初始速度 19 p = 0.3 # 随机减速概率 20 Times = 3000 21 22 np.random.seed(0) 23 x = np.random.rand(n) * path 24 x.sort() 25 v = np.tile([v0], n).astype(np.float) 26 27 plt.figure(figsize=(9, 7), facecolor='w') 28 for t in range(Times): 29 plt.scatter(x, [t]*n, s=1, c='k', alpha=0.05) 30 for i in range(n): 31 if x[(i+1)%n] > x[i]: 32 d = x[(i+1) % n] - x[i] # 距离前车的距离 33 else: 34 d = path - x[i] + x[(i+1) % n] 35 if v[i] < d: 36 if np.random.rand() > p: #随机减速 37 v[i] += 1 38 else: 39 v[i] -= 1 40 else: 41 v[i] = d - 1 42 v = v.clip(0, 150) 43 x += v 44 clip(x, path) 45 plt.xlim(0, path) 46 plt.ylim(0, Times) 47 plt.xlabel('车辆位置', fontsize=14) 48 plt.ylabel('模拟时间', fontsize=14) 49 plt.title('环形公路车辆堵车模拟', fontsize=18) 50 plt.tight_layout(pad=2) 51 plt.show()