Skip to content Skip to sidebar Skip to footer

Python Program That Rolls A Fair Die Counts The Number Of Rolls Before A 6 Shows Up

import random sample_size = int(input('Enter the number of times you want me to roll the die: ')) if (sample_size <=0): print('Please enter a positive number!') else:

Solution 1:

import random

whileTrue:
  sample_size = int(input("Enter the number of times you want me to roll a die: "))
  if sample_size > 0:
    break

roll_with_6 = 0
roll_count = 0while roll_count < sample_size:
  roll_count += 1
  n = random.randint(1, 6)
  #print(n)if n == 6:
    roll_with_6 += 1print(f'Probability to get a 6 is = {roll_with_6/roll_count}')

One sample output:

Enter the number of times you want meto roll a dile: 10
Probability toget a 6is = 0.2

Another sample output:

Enter the number of times you want meto roll a die: 1000000
Probability toget a 6is = 0.167414

Solution 2:

Sticking with your concept, I would create a list that contains each roll then use enumerate to count the amount of indices between each 1 and sum those, using the indicies as markers.

the variable that stores the sum of the number of rolls it took before a 1 showed up - OP

from random import randint

sample_size = 0while sample_size <= 0:
    sample_size = int(input('Enter amount of rolls: '))

l = [randint(1, 6) for i inrange(sample_size)]

start = 0
count = 0for idx, item inenumerate(l):
    if item == 1:
        count += idx - start
        start = idx + 1print(l)
print(count)
print(count/sample_size)
Enter amount of rolls: 10
[5, 3, 2, 6, 2, 3, 1, 3, 1, 1]
70.7

Sameple Size 500:

Enter amount of rolls:5004060.812

Post a Comment for "Python Program That Rolls A Fair Die Counts The Number Of Rolls Before A 6 Shows Up"