Python - 重复有偏见的硬币翻转实验

时间:2017-02-04 02:17:49

标签: python function for-loop simulation coin-flipping

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

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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

答案 2 :(得分: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))