Python Forum
Question code from datacamp I don't understand
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Question code from datacamp I don't understand
#1
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
Reply
#2
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]
Reply
#3
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?
Reply
#4
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
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  KNN algorithm Assignment can't understand the question spoooder 6 2,889 May-25-2020, 11:19 AM
Last Post: jefsummers
  Intro to Python for Data Science with Datacamp Sabrusura 4 3,623 Aug-21-2018, 09:03 AM
Last Post: Sabrusura

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020