So, the exercise is centered around a game that will tell in which step of a building you will be. You throw a die 100x and if the number is less than or equal to 2, you fall one step (if you are in step 0, you will stay in step 0), if it is higher than 2 and less than or equal to 5, you climb one step. If the number is 6, you throw the die again and will climb the resulting number of steps.
The following code simulates this game 20x. The exercise also says the following: “There’s still something we forgot
! You’re a bit clumsy and you have a 0.5% chance of falling down. That calls for another random number generation
. Basically, you can generate a random float between 0 and 1. If this value is less than or equal to 0.005, you should reset step to 0”. I didn’t understand this last part, and will show the code that solves the exercise for clarification.
# clear the plot so it doesn't get cluttered if you run this many times
plt.clf()
# Simulate random walk 20 times
all_walks = []
for i in range(20) :
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)
# Implement clumsiness
if np.random.rand() <= 0.005 :
step = 0
random_walk.append(step)
all_walks.append(random_walk)
# Create and plot np_aw_t
np_aw_t = np.transpose(np.array(all_walks))
plt.plot(np_aw_t)
plt.show()```
Diogo Lamounier is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
1