Python Forum
Question code from datacamp I don't understand - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Homework (https://python-forum.io/forum-9.html)
+--- Thread: Question code from datacamp I don't understand (/thread-8045.html)



Question code from datacamp I don't understand - fad3r - Feb-04-2018

Hi,
I don't need any help coding anything I just really am confused on this code:

import numpy as np
np.random.seed(123)
tails = [0]
for x in range(10) :
    coin = np.random.randint(0, 2)
    tails.append(tails[x] + coin)
print(tails)
It prints out: [0, 0, 1, 1, 1, 1, 1, 1, 2, 3, 3]

Supposedly this is an example of somehing called a "random walk"

I am a little confused on the tails.append line and the output. I am confused on why there are 11 items and how this manages to ignore the heads aspect. It only tracks tails. I didn't find the video very clear at all.

Thanks


RE: Question code from datacamp I don't understand - Larz60+ - Feb-04-2018

tails = [0] this creates a list with a single element of 0.
When you append, it adds additional values.
start with tails = []
Then change:
tails.append(tails[x] + coin)
to
tails.append(coin)
>>> import numpy as np
>>> np.random.seed(123)
>>> tails = []
>>> for x in range(10):
...     coin = np.random.randint(0, 2)
...     tails.append(coin)
...
>>> tails
[0, 1, 0, 0, 0, 0, 0, 1, 1, 0]



RE: Question code from datacamp I don't understand - fad3r - Feb-04-2018

What is tails[x] doing I guess?

I thought that it is coming from range tails[1], tails[2]

Is that to move us through to tails[10]?

And the idea is since zero is heads it never gets added but since tails is 1 we increase by 1 each time?


RE: Question code from datacamp I don't understand - buran - Feb-04-2018

it tracks how many times (total) you get tails when flip a coin 10 times in a row. so you have random number 0 or 1 - 1 means you get a tail, 0 - a head. Every time you get 1 (i.e. tail), it increase the last element by 1. you get 11 elements because you start from 10 and then toss the coin 10 times