CommencerCommencer gratuitement

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

Afficher le cours

Instructions

  • Utilisez np.array() pour convertir all_walks en un tableau NumPy, np_aw.
  • Essayez d'utiliser plt.plot() sur np_aw. Incluez également plt.show(). Est-ce qu'il fonctionne immédiatement ?
  • Transposez np_aw en appelant np.transpose() sur np_aw. Appelez le résultat np_aw_t. Maintenant, chaque ligne de np_all_walks représente la position après un lancer pour les cinq marches aléatoires.
  • Utilisez plt.plot() pour tracer np_aw_t ; incluez également plt.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
Modifier et exécuter le code