1
\$\begingroup\$

I am not 100% sure that I am using the random.seed correctly for this assignment, or if there is a more efficient way to write the code. Any feedback is appreciated.

Assignment Description: Simulate rolling 2 die one hundred times. Keep track of the total of the two die. Print a histogram in which the total number of times the dice rolls equals each possible value is displayed by printing a character, such as *, that number of times

import random
random.seed(2)
# declaring an array to count the occurrences
a= [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

# looping for 100 times and saving the count in array
for i in range(100):
    x = random.randint(1,6)
    y = random.randint(1,6)
    a[x+y] = a[x+y] + 1

# printing histogram  
for i in range(2, 13):
    print(str(i).rjust(2)+"s: ","*"*a[i])
\$\endgroup\$
  • 4
    \$\begingroup\$ "for this assignment" What is the assignment description? \$\endgroup\$ – Mast Nov 20 '18 at 14:24
  • \$\begingroup\$ Apologies, I meant for a school assignment. I will edit the post to include the assignment description. \$\endgroup\$ – mcinnis_k Nov 21 '18 at 10:35
6
\$\begingroup\$

Various small comments:

  • you can write a[x+y] += 1
  • you always call random.seed with the same input so you'll always have the same output. You could call it with no value so that it uses the time (which is different from one run to another).
  • instead of having an explicit 13 at the end of your code, you could use len(a)
  • you could use a constant to store 100 to avoid having a magic number in the middle of your code
  • you could use a constant to store the number of faces per dice
  • you could initialise a by using list multiplication. In particular, you could reuse the constant introduced just before.

At this stage, you have:

NB_ITER = 100
DICE_MAX_NUM = 6

random.seed()

# declaring an array to count the occurrences
a= [0] * (2 * DICE_MAX_NUM + 1)

# looping and saving the count in array
for i in range(NB_ITER):
    val = random.randint(1, DICE_MAX_NUM) + random.randint(1, DICE_MAX_NUM)
    a[val] += 1

# printing histogram
for i in range(2, len(a)):
    print(str(i).rjust(2) + "s: ", "*" * a[i])

To be continued but you could use collections.Counter...

\$\endgroup\$
  • 2
    \$\begingroup\$ +1 on the Counter \$\endgroup\$ – Maarten Fabré Nov 21 '18 at 11:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.