Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/local/bin/python
- # -*- coding: utf-8 -*-
- from __future__ import division
- from operator import mul
- def P(m,n):
- '''
- 基本概率计算: P(E)
- '''
- return m/n
- def per(n):
- '''
- 计算阶乘
- '''
- return reduce(mul,range(n,0,-1))
- def combination(n,r):
- '''
- 计算组合
- '''
- return per(n)/( per(r)*per(n-r) )
- import unittest
- class TestPermutations(unittest.TestCase):
- def setUp(self):
- pass
- def testPer(self):
- self.assertEqual(per(5),5*4*3*2*1)
- def testComb(self):
- self.assertEqual(combination(n=4,r=2),6)
- self.assertEqual(int(round(combination(n=49,r=6))),13983816)
- def testBasicpe(self):
- '''
- P(掷一公平骰子得出6)=1/6
- '''
- self.assertEqual(P(1,6),1.0/6.0)
- def testAdd(self):
- '''
- 加法定理验证
- 如果掷两粒公平骰子,擲出2和4的概率分别是多少?
- '''
- self.assertEqual( P(1,36),1/36 )
- self.assertEqual( P(1,36)+P(1,36)+P(1,36),3/36 )
- def testMultiplication(self):
- '''
- 乘法定理验证
- 假设掷三粒公平骰子所得出数字之积为k。P(k是奇数)是多少?
- P(k是奇数)=P(第一个数是奇数)*P(第二个数是奇数)*P(第三个数是奇数)=3/6*3/6*3/6=1/8
- '''
- self.assertEqual( P(3,6)*P(3,6)*P(3,6),1/8 )
- if __name__ == '__main__':
- unittest.main()
Add Comment
Please, Sign In to add comment