# 15.3.1 create RandomWalk ()
From the random import choice
The class RandomWalk () :
"" "a generated random walk data class ", "
Def __init__ (self, num_points=5000) :
"" "initialization properties of random walk "" "
Self. Num_points=num_points
Self. X_values=[0] # all random walks in (0, 0)
Self. Y_values=[0]
Def fill_walk (self) :
"" "computing random walk contains all points "" "
# walk continuously, until the list reaches the specified length
While len (self x_values) & lt; Self. Num_points:
# decides the direction and distance along this direction
X_direction=choice ([1, 1])
,1,2,3,4 x_distance=choice ([0])
X_step=x_direction * x_distance
Y_direction=choice ([1, 1])
,1,2,3,4 y_distance=choice ([0])
Y_step=y_direction * y_distance
# refused to mark time
If x_step==0 and y_step==0:
The continue
# computing the next point of x and y values
Next_x=self. X_values [1] + x_step
Next_y=self. Y_values [1] + y_step
Self. X_values. Append (next_x)
Self. Y_values. Append (next_y)
# to create a RandomWalk instance, and include them points are mapped
Rw=RandomWalk () # why RandomWalk instance without argument?
Rw. Fill_walk ()
PLT. Scatter (rw) x_values, rw. Y_values, s=15)
PLT. The show ()
CodePudding user response:
Because RandomWalk init num_points assignment for 5000 already inside, don't need to preach to participate, you can modify the code to pass arguments at the following:
From the random import choice
The import matplotlib. Pyplot as PLT
The class RandomWalk () :
"" "a generated random walk data class ", "
Def __init__ (self, num_points) :
"" "initialization properties of random walk "" "
Self. Num_points=num_points
Self. X_values=[0] # all random walks in (0, 0)
Self. Y_values=[0]
Def fill_walk (self) :
"" "computing random walk contains all points "" "
# walk continuously, until the list reaches the specified length
While len (self x_values) & lt; Self. Num_points:
# decides the direction and distance along this direction
X_direction=choice ([1, 1])
,1,2,3,4 x_distance=choice ([0])
X_step=x_direction * x_distance
Y_direction=choice ([1, 1])
,1,2,3,4 y_distance=choice ([0])
Y_step=y_direction * y_distance
# refused to mark time
If x_step==0 and y_step==0:
The continue
# computing the next point of x and y values
Next_x=self. X_values [1] + x_step
Next_y=self. Y_values [1] + y_step
Self. X_values. Append (next_x)
Self. Y_values. Append (next_y)
# to create a RandomWalk instance, and include them points are mapped
Rw=RandomWalk (# 5000) to send and assignment to num_points
Rw. Fill_walk ()
PLT. Scatter (rw) x_values, rw. Y_values, s=15)
PLT. The show ()