Oct-04-2020, 01:07 PM
(This post was last modified: Oct-04-2020, 01:07 PM by deanhystad.)
You are having a hard time understanding the code because the code is stupid. This does the same thing in a straight forward way.
I was surprised to learn that random.randint and np.random.randint are different.
import random final_tails = [] for x in range(100) : tails = 0 for x in range(10) : tails += random.randint(0, 1) final_tails.append(tails) print(final_tails)Instead of counting the number of tails using an integer, the program saves the tails count as a history list. To show this I expanded the inner loop:
import random results = ['Heads', 'Tails'] final_tails = [] tails = [0] for x in range(10) : coin = random.randint(0, 1) tails.append(tails[x] + coin) print(results[coin], tails)
Output:Heads [0, 0]
Heads [0, 0, 0]
Heads [0, 0, 0, 0]
Tails [0, 0, 0, 0, 1]
Tails [0, 0, 0, 0, 1, 2]
Heads [0, 0, 0, 0, 1, 2, 2]
Tails [0, 0, 0, 0, 1, 2, 2, 3]
Heads [0, 0, 0, 0, 1, 2, 2, 3, 3]
Heads [0, 0, 0, 0, 1, 2, 2, 3, 3, 3]
Heads [0, 0, 0, 0, 1, 2, 2, 3, 3, 3, 3]
The list "tails" is how many tails have occurred so far. tails[-1] is the last value after ten coin flips. Looking back at the original code, "final_tails" is a collection of how many times the coin comes up tails when flipped 10 times.I was surprised to learn that random.randint and np.random.randint are different.