Solution: Rolling a Dice#

Write a function that works as a dice-rolling simulator.

Rules#

  1. Dice type: Cube (6 faces).

  2. Dice is fair: equal chance of rolling any value.

  3. The function must return an integer value corresponding to the rolled face.

  4. You can use any function from the random module

Function definition#

from random import randint

def dice_rolling():
    face = randint(1,6)
    return face
from random import choice

def dice_rolling():
    face = choice([1,2,3,4,5,6])
    return face

Testing#

Check if your function returns the expected value using the cell below.

import unittest
import numpy as np

class UnitTests(unittest.TestCase):
    def test_type(self):
        self.assertTrue(isinstance(dice_rolling(), int), 'The function should return an integer')
    def test_min_value(self):
        self.assertTrue(all(dice_rolling() >= 1 for _ in range(1000)), 'The function should return a minimum value of 1')
    def test_max_value(self):
        self.assertTrue(all(dice_rolling() <= 6 for _ in range(1000)), 'The function should return a maximum value of 6')
    def test_uniform_distribution(self):
        faces = [dice_rolling() for _ in range(100000)]
        hist, edges = np.histogram(faces, bins=[1,2,3,4,5,6,7], density=True)
        for i in range(6):
            self.assertAlmostEqual(hist[i], 1/6, places=2, msg=f'The side {i+1} should be rolled with a probability of 0.16')

unittest.main(argv=[''], verbosity=2,exit=False)
test_max_value (__main__.UnitTests) ... 
ok
test_min_value (__main__.UnitTests) ... 
ok
test_type (__main__.UnitTests) ... 
ok
test_uniform_distribution (__main__.UnitTests) ... 
ok

----------------------------------------------------------------------
Ran 4 tests in 0.110s

OK
<unittest.main.TestProgram at 0x7f889c10cf10>