Visualize all walks
all_walks is a list of lists: every sub-list represents a single random walk. If you convert this list of lists to a NumPy array, you can start making interesting plots! matplotlib.pyplot is already imported as plt.
The nested for loop is already coded for you - don't worry about it. For now, focus on the code that comes after this for loop.
Diese Übung ist Teil des Kurses
Intermediate Python
Anleitung zur Übung
- Use
np.array()to convertall_walksto a NumPy array,np_aw. - Try to use
plt.plot()onnp_aw. Also includeplt.show(). Does it work out of the box? - Transpose
np_awby callingnp.transpose()onnp_aw. Call the resultnp_aw_t. Now every row innp_aw_trepresents the position after 1 throw for the five random walks. - Use
plt.plot()to plotnp_aw_t; also include aplt.show(). Does it look better this time?
Interaktive Übung
Vervollständige den Beispielcode, um diese Übung erfolgreich abzuschließen.
# numpy and matplotlib imported, seed set.
# initialize and populate all_walks
all_walks = []
for i in range(5) :
random_walk = [0]
for x in range(100) :
step = random_walk[-1]
dice = np.random.randint(1,7)
if dice <= 2:
step = max(0, step - 1)
elif dice <= 5:
step = step + 1
else:
step = step + np.random.randint(1,7)
random_walk.append(step)
all_walks.append(random_walk)
# Convert all_walks to NumPy array: np_aw
# Plot np_aw and show
# Clear the figure
plt.clf()
# Transpose np_aw: np_aw_t
# Plot np_aw_t and show