I'm studying Python steadily at freeCodeCamp. In Previous article, this time we will challenge * Probability Calculator *.
This problem is a problem that seems to have been solved as a probability problem when I was a student. Find the probability of taking out multiple colored balls in a hat (bag). In particular,
--Creating a Hat class --Creating an experiment method: A method for finding the probability
This time, there is a process of randomly taking out the ball from the hat. It doesn't work when I want to write a test like below.
1 import unittest
2
3 class UnitTests(unittest.TestCase):
4 #When you take out 2 balls from a hat with 5 red balls and 2 blue balls, there is 1 red ball and 1 blue ball.
5 def test_hat_draw(self):
6 hat = prob_calculator.Hat(red=5,blue=2)
7 actual = hat.draw(2)
8 expected = ['blue', 'red']
9 self.assertEqual(actual, expected, 'Expected hat draw to return two random items from hat contents.')
10 actual = len(hat.contents)
11 expected = 5
12 self.assertEqual(actual, expected, 'Expected hat draw to reduce number of items in contents.')
When you draw two balls on the 7th line, the internal implementation uses random numbers, so there is not always one red ball and one blue ball. Use `random seed`` to solve this.
import random
balls = ['red', 'red', 'red', 'red', 'red', 'blue', 'blue']
random.sample(balls, k=2)
# ['red', 'red']
random.sample(balls, k=2)
# ['red', 'blue']
random.seed(0)
random.sample(balls, k=2)
# ['blue', 'red']
random.seed(0)
random.sample(balls, k=2)
# ['blue', 'red']
By setting the seed of random numbers in advance in this way, the same behavior can always be achieved.
Scientific Computing with Python is over! Next, I'm going to start doing Data Analysis with Python Certification!
Recommended Posts