examples
Python Exercise : Rolling The Dice
Python exercise
Episode: 3
Level: Intermediate
What do you think how many times you have to roll the dice to get each number (1 - 6) at least two times? How about 3 times or more? Write a Python program to find out.
First we have to import random library. We are interested in randint(a, b) method since our dice can produce numbers from 1 to 6.
We need two functions, game function and tests function. Finally we need to call tests function to get the results.
Inside game function we need 2 variables, one list of same six numbers and counter. The idea is to have list like this L = [2, 2, 2, 2, 2, 2]. When we roll the dice and let's say get number 5, we will subtract 1 from fifth element in the list, so our list will look like this L = [2, 2, 2, 2, 1, 2]. We add 1 to counter.
When sum of list elements is zero, this means we got all numbers at least twice. Print counter and you are done.
Tests function will have two parameters. One to choose how many times we want every number to appear and second parameter is number of cycles. More cycles means better average number and precise result. Please be aware if your computer can handle large numbers. Start small and than increase.
OK, now let's see the code.
import random
def game(rep):
l = [rep for i in range(6)]
counter = 0
def roll():
return random.randint(1, 6)
def check_list(lst):
return sum(lst) == 0
while(not check_list(l) ):
n = roll()
if l[n - 1] > 0:
l[n - 1] -= 1
counter += 1
return counter
def tests(g, times):
result = [game(g) for j in range(times)]
average = str(sum(result) / times)
print("Average number of rolls is: " + average)
Here are my results:
tests(1, 100000) > 14,7
This means if you want to get all numbers from 1 to 6, you have to roll the dice on average 14,7 times! This is very precise number since I've done 100.000 tests here.
If you want to get all numbers at least twice you need to roll the dice on average 24,1 times.
tests(2, 100000) > 24,1
tests(3, 100000) > 32,6
tests(4, 100000) > 40,7
tests(5, 100000) > 48,6
tests(6, 100000) > 56,2
As you can see there are 8 more rolls for every next level after 2.
Now you know it.
Thanks for your time.


Post a Comment
0 Comments
Thanks for sharing your thoughts !