主程序
1 import matplotlib.pyplot as plt
2 from randomwalk import RandomWalk
3
4 rw = RandomWalk()
5 rw.fill_walk()
6 plt.style.use('seaborn')
7 fig, ax = plt.subplots()
8 points_numbers = range(rw.num_points)
9 ax.scatter(rw.x_values, rw.y_values, c=points_numbers,
10 cmap=plt.cm.Blues, s=15)
11 ax.get_xaxis().set_visible(False)
12 ax.get_yaxis().set_visible(False)
13
14 plt.show()
randomwalk.py
1 from random import choice
2
3 class RandomWalk:
4 def __init__(self, num_points=5000):
5 self.num_points = num_points
6 self.x_values = [0]
7 self.y_values = [0]
8
9 def fill_walk(self):
10 while len(self.x_values) < self.num_points:
11 x_direction = choice([-1, 1])
12 x_distance = choice([0, 1, 2, 3, 4])
13 x_step = x_direction * x_distance
14
15 y_direction = choice([-1, 1])
16 y_distance = choice([0, 1, 2, 3, 4])
17 y_step = y_direction * y_distance
18
19 if x_step==0 and y_step==0:
20 continue
21
22 x = self.x_values[-1] + x_step
23 y = self.y_values[-1] + y_step
24
25 self.x_values.append(x)
26 self.y_values.append(y)
get_step()重构
1 from random import choice
2
3 class RandomWalk:
4 def __init__(self, num_points=5000):
5 self.num_points = num_points
6 self.x_values = [0]
7 self.y_values = [0]
8
9 def get_step(self):
10 direnction = choice([-1, 1])
11 distance = choice([0, 1, 2, 3, 4])
12 step = direction * distance
13 return step
14
15 def fill_walk(self):
16 while len(self.x_values) < self.num_points:
17 x_step = self.get_step()
18 y_step = self.get_step()
19
20 if x_step==0 and y_step==0:
21 continue
22
23 x = self.x_values[-1] + x_step
24 y = self.y_values[-1] + y_step
25
26 self.x_values.append(x)
27 self.y_values.append(y)