IPY-2: Intermediate Python (random walk)
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 therandom_walk
list. You can use the index-1
for this. - Next, let the
if
-elif
-else
construct updatestep
for you. - The code that appends
step
torandom_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.
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!!
Latest Post: Need help on the quiz: AI4I-2-Q: Libraries and Data Manipulation Quiz Our newest member: John Eric Recent Posts Unread Posts Tags
Forum Icons: Forum contains no unread posts Forum contains unread posts
Topic Icons: Not Replied Replied Active Hot Sticky Unapproved Solved Private Closed