样本空间与概率 ¶
In [1]:
Copied!
import math
a = 1
b = 2
print(a + b)
import math
a = 1
b = 2
print(a + b)
3
条件概率 ¶
例:一个班有 4 个本科生和 12 个研究生,随机将他们分成 4 个 4 人组,每组分到一个本科生的概率多大?
先建立数组,再打乱数组,再统计满足条件的概率。
In [2]:
Copied!
import random
import numpy as np
a = [1, 0]
s = [4, 12]
result = np.repeat(a, s)
result.reshape(4, 4)
k = 0
sample = 10000
for j in range(sample):
random.shuffle(result) # 随机排列,改变result的值
result2d = result.reshape(4, 4) # 分为4组
k += np.prod([i.sum() for i in result2d]) # 每组总和均为1时为真
print(k / sample)
import random
import numpy as np
a = [1, 0]
s = [4, 12]
result = np.repeat(a, s)
result.reshape(4, 4)
k = 0
sample = 10000
for j in range(sample):
random.shuffle(result) # 随机排列,改变result的值
result2d = result.reshape(4, 4) # 分为4组
k += np.prod([i.sum() for i in result2d]) # 每组总和均为1时为真
print(k / sample)
0.1392
全概率定理 ¶
贝叶斯定理 ¶
排列组合 ¶
In [3]:
Copied!
# 法一: math 库
for k in range(5):
p0 = math.perm(5, k) # permutation 排列
p1 = math.comb(5, k) # combination 组合
print("5选", k, ", 排列 ", p0, ", 组合 ", p1)
# 法一: math 库
for k in range(5):
p0 = math.perm(5, k) # permutation 排列
p1 = math.comb(5, k) # combination 组合
print("5选", k, ", 排列 ", p0, ", 组合 ", p1)
5选 0 , 排列 1 , 组合 1 5选 1 , 排列 5 , 组合 5 5选 2 , 排列 20 , 组合 10 5选 3 , 排列 60 , 组合 10 5选 4 , 排列 120 , 组合 5
In [4]:
Copied!
# 法二: itertools 库
import itertools
for k in range(5):
p0 = len(list(itertools.permutations(range(5), k)))
p1 = len(list(itertools.combinations(range(5), k)))
print("5选", k, ", 排列 ", p0, ", 组合 ", p1)
# 法二: itertools 库
import itertools
for k in range(5):
p0 = len(list(itertools.permutations(range(5), k)))
p1 = len(list(itertools.combinations(range(5), k)))
print("5选", k, ", 排列 ", p0, ", 组合 ", p1)
5选 0 , 排列 1 , 组合 1 5选 1 , 排列 5 , 组合 5 5选 2 , 排列 20 , 组合 10 5选 3 , 排列 60 , 组合 10 5选 4 , 排列 120 , 组合 5
In [5]:
Copied!
# 法3: scipy 库
import scipy.special as sp
print(sp.binom(4, 3)) # 5选2
# 法 3: scipy 库
import scipy.special as sp
print(sp.binom(4, 3)) # 5选2
4.0