Visualisez toutes les marches
all_walks
est une liste de listes : chaque sous-liste représente une marche aléatoire unique. Si vous convertissez cette liste de listes en un tableau NumPy, vous pouvez commencer à faire des tracés intéressants. matplotlib.pyplot
est déjà importé en tant que plt
.
La boucle imbriquée for
est déjà codée pour vous, ne vous en préoccupez pas. Pour l'instant, concentrez-vous sur le code qui suit cette boucle for
.
Cet exercice fait partie du cours
Python intermédiaire
Instructions
- Utilisez
np.array()
pour convertirall_walks
en un tableau NumPy,np_aw
. - Essayez d'utiliser
plt.plot()
surnp_aw
. Incluez égalementplt.show()
. Est-ce qu'il fonctionne immédiatement ? - Transposez
np_aw
en appelantnp.transpose()
surnp_aw
. Appelez le résultatnp_aw_t
. Maintenant, chaque ligne denp_all_walks
représente la position après un lancer pour les cinq marches aléatoires. - Utilisez
plt.plot()
pour tracernp_aw_t
; incluez égalementplt.show()
. Le résultat est-il meilleur cette fois-ci ?
Exercice interactif pratique
Essayez cet exercice en complétant cet exemple de code.
# 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