【发布时间】:2023-12-23 05:51:02
【问题描述】:
我正在尝试编写一个函数来模拟 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'
【问题讨论】:
-
“不起作用”是什么意思?
Outcome/X(将列表除以一个整数——不是一个东西)可能是其中的一部分,但还有其他什么? -
它对我有用!你期待什么,你得到什么让你觉得这行不通!
-
我收到以下错误
TypeError: unsupported operand type(s) for /: 'list' and 'int' -
我发现发生了:
Outcome是之前定义的,我完全忘记了它。 >.>
标签: python function for-loop simulation coin-flipping