我正在尝试编写一个模拟 X 次有偏硬币翻转实验(H=0.6,T=0.4)的函数,该实验由 N 次硬币翻转组成,以回答问题“之后的组数的期望值是多少N个硬币翻转。” 根据定义,组是连续顺序中相同值的最大序列。
例如:['H', 'H', 'H', 'H', 'H', 'H', 'T', 'H', 'H', 'H']
有3组,['T', 'H', 'H', 'H', 'T', 'T', 'H', 'H', 'H', 'H']
有4组。
# Libraries
import random
from itertools import groupby
from itertools import chain
# Function for biased coin
def flip(p):
return 'H' if random.random() < p else 'T'
# Number of coin flips
N = 10
flips = [flip(0.6) for i in range(N)]
print (len(list(groupby(flips))))
# Function to simulate X iterations of N coin flips
def simulate(X, N):
Outcome = [] # Empty list to store each experiment's result
# X Number of coin simulations
for i in range(X):
# Coin simulation of N flips
flips = [flip(0.6) for j in range(N)]
# Append experiment's result into Outcome list
Outcome.append(len(list(groupby(flips))))
# Expected Value of the number of groups
sum(Outcome)/X
知道为什么这不起作用吗?我收到以下错误TypeError: unsupported operand type(s) for /: 'list' and 'int'