0

我正在尝试编写一个模拟 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'

4

3 回答 3

1

您正在将列表除以一个数字。你需要在你的函数中使用 return 。

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))))
    X = float(X)
    # Expected Value of the number of groups
    return sum(Outcome)/X
于 2017-02-04T02:31:45.213 回答
1

您正在尝试取结果的平均值,因此您不想将它们存储在列表中,而是要将它们相加并除以试验次数。

def simulate(x, n):
    outcome = 0.0
    for i in range(x):
        flips = [flip(0.6) for j in range(n)]
        outcome += len(list(groupby(flips)))
    return outcome / x
于 2017-02-04T02:33:40.077 回答
0
# 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 = []
    for i in range(X):
        flips = [flip(0.6) for j in range(N)]
        Outcome.append(len(list(groupby(flips))))
    print(sum(Outcome)/(X))
于 2017-02-04T02:33:27.767 回答