Forum

Notifications
Clear all

IPY-2: Intermediate Python (random walk)  

   RSS

0

There is an exercise on Random Walk.
The instruction is:-

  • Make a list random_walk that contains the first step, which is the integer 0.
  • Finish the for loop:
  • The loop should run 100 times.
  • On each iteration, set step equal to the last element in the random_walk list. You can use the index -1 for this.
  • Next, let the if-elif-else construct update step for you.
  • The code that appends step to random_walk is already coded.
  • Print out random_walk.

By following the instruction, I have no issue with coding it correctly. Blue font is what I typed in. Code that was already provided in the datacamp exercise is in black font. 

# Numpy is imported, seed is set

# Initialize random_walk
random_walk = [0]

# Complete the 
for x in range(100) :
 
    # Set step: last element in random_walk
    step = random_walk[-1]

    # Roll the dice
    dice = np.random.randint(1,7)

    # Determine next step
    if dice <= 2:
        step = step - 1
    elif dice <= 5:
        step = step + 1
    else:
        step = step + np.random.randint(1,7)

    # append next_step to random_walk
    random_walk.append(step)

# Print random_walk
print(random_walk)
 

The result/output is:
[0, 3, 4, 5, 4, 5, 6, 7, 6, 5, 4, 3, 2, 1, 0, -1, 0, 5, 4, 3, 4, 3, 4, 5, 6, 7, 8, 7, .... .... so on ...]

I was trying to understand why do we do this "set step equal to the last element in the random_walk list". I think, I got the idea, but would like to check if my understanding is correct.

My explanation:
Based on the result/output from the code, the first element is 0 because we set "random_walk = [0]".

The 2nd element is "3" which means, when the code runs the first loop (X=1), #roll the dice segment generated a 6, hence it hits the else portion of the #determine next step segment and at this point, the dice generated eye 3. Hence, after the first loop (x=1), step = 0 +3 = 3.

At this point, random_walk has 2 values, first one is 0 and 2nd one is 3. 

On 2nd loop (X=2), we pick step =3 (because this is the last element in the random_walk) and # Roll the dice segment generated dice eye of either 3,4 or 5. Hence, the elif portion is executed. Resulting step = 3 +1 = 4. 

random_walk list is now [0, 3, 4].

 

This goes on....

 

Is my understanding correct? 

 

Thank you!!

Share:

Delete your account