Skip to content
Advertisement

Listing each iteration of rolling a six-sided-die in Python

I’m working on an animated bar plot to show how the number frequencies of rolling a six-sided die converge the more you roll the die. I’d like to show the number frequencies after each iteration, and for that I have to get a list of the number frequencies for that iteration in another list. Here’s the code so far:

import numpy as np
import numpy.random as rd

rd.seed(23)
n_samples = 3
freqs = np.zeros(6)
frequencies = []

for roll in range(n_samples):
  x = rd.randint(0, 6)
  freqs[x] += 1
  print(freqs)
  frequencies.append(freqs)

print()

for x in frequencies:
    print(x)

Output:

[0. 0. 0. 1. 0. 0.]
[1. 0. 0. 1. 0. 0.]
[1. 1. 0. 1. 0. 0.]

[1. 1. 0. 1. 0. 0.]
[1. 1. 0. 1. 0. 0.]
[1. 1. 0. 1. 0. 0.]

Desired output:

[0. 0. 0. 1. 0. 0.]
[1. 0. 0. 1. 0. 0.]
[1. 1. 0. 1. 0. 0.]

[0. 0. 0. 1. 0. 0.]
[1. 0. 0. 1. 0. 0.]
[1. 1. 0. 1. 0. 0.]

The upper three lists indeed show the number frequencies after each iteration. However, when I try to append the list to the ‘frequencies’ list, in the end it just shows the final number frequencies each time as can be seen in the lower three lists. This one’s got me stumped, and I am rather new to Python. How would one get each list like in the first three lists of the output, in another? Thanks in advance!

Advertisement

Answer

Python is keeping track of freqs as single identity, and its value gets changed even after it gets appended. There is a good explanation for this beyond my comprehension =P

However, here is quick and dirty work around:

import numpy as np
import numpy.random as rd

rd.seed(23)
n_samples = 3
freqs = np.zeros(6)
frequencies = []

for roll in range(n_samples):
  x = rd.randint(0, 6)
  freqs_copy = []
  for item in freqs:
      freqs_copy.append(item)
  freqs_copy[x] += 1
  print(freqs_copy)
  frequencies.append(freqs_copy)

print()

for x in frequencies:
    print(x)

The idea is to make a copy of “freqs” that would be independent of original “freqs”. In the code above “freqs_copy” would be unique to each iteration.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement