IPY-2: Intermediate Python (random walk)
There is an exercise on Random Walk.
The instruction is:-
- Make a list
random_walkthat contains the first step, which is the integer 0.
- Finish the
- The loop should run
- On each iteration, set
stepequal to the last element in the
random_walklist. You can use the index
- Next, let the
- The code that appends
random_walkis already coded.
- Print out
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.
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.
Based on the result/output from the code, the first element is 0 because we set "random_walk = ".
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?