LoginSignup
1
1

More than 3 years have passed since last update.

Pythonでの乱数があるときのテスト

Posted at

Scientific Computing with Pythonの続き

freeCodeCampでコツコツPythonを勉強しています。
前回の記事では、今回はProbability Calculatorに挑戦します。

  • Python for Everybody
  • Scientific Computing with Python Projects
    • Arithmetic Formatter
    • Time Calculator
    • Budget App
    • Polygon Area Calculator
    • Probability Calculator(今回はここ)

5問目:Probability Calculator

今回の問題は、学生の時くらいに確率の問題で解いたことがありそうな問題。
帽子(袋)に入っている色付きボールを複数個取り出したときの確率を求める。
具体的には、

  • Hatクラスの作成
  • experimentメソッドの作成: 確率を求めるためのメソッド

個人的ポイント: 乱数を使ったときのテスト

今回は帽子の中からランダムにボールを取り出すという処理があります。
以下のようなテストを書きたいときにうまくいきません。

 1 import unittest
 2 
 3 class UnitTests(unittest.TestCase):
 4     # 赤い玉が5個、青い玉が2個入った帽子から2つボールを取り出したとき、赤い玉が1つ、青い玉が1つであること
 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.')

7行目で2つボールをひく時、内部の実装では乱数を使っているので、必ずしも赤い玉が1つ、青い玉が1つであるとは限らないです。
これを解決するために乱数のシードを使います。


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']

このように事前に乱数のシードを設定することによって、常に同じ挙動をさせることができます。

最後に

Scientific Computing with Pythonが一通り終わった!
次はData Analysis with Python Certificationをやり始めようと思います!

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1