【问题标题】:Python - For Loop and If Statement in calculating probability in coin tossPython - 用于计算抛硬币概率的 For 循环和 If 语句
【发布时间】:2017-06-23 00:44:15
【问题描述】:

这里的 Python 相当新。我正在尝试计算发生有偏见的抛硬币事件的条件概率。除了if statement 部分之外,我已经弄清楚了大部分代码——具体来说,我不确定是使用pass 还是continue。更具体地说,我希望分母反映满足要求的迭代次数,而不是总迭代次数。

例如,假设我想计算 6 组的概率,假设我们在 10 次抛硬币后超过 5 组 - 该函数将读取为 simulate_three(1000,10,6,5),其中参数表示 1000 次迭代、10 次抛硬币、6 组, 和 5 组,分别。假设只有 500 次迭代满足要求 - 因此,Outcome 的分母是 500,而不是 1000。但是,我不确定代码是否正常工作......

import random
from itertools import groupby
import statistics

# Function for biased coin
def flip(p):
return 'H' if random.random() < p else 'T'

# Simulation
def simulate_three(X, N, Y, Z):
    Outcome = [] # List of results
    for i in range(X): # For loop for the X number of iterations
        flips = [flip(0.6) for j in range(N)] # For loop for N number of coin flips
        if len(list(groupby(flips))) <= Z: # If group condition isn't met
            pass                           # Don't store value and skip
        Outcome.append(len(list(groupby(flips)))) # Otherwise, store to list
    print(sum(Outcome)/(len(Outcome)))     # Print expected value
    print((Y-(sum(Outcome)/(len(Outcome))))/statistics.stdev(Outcome)) # Print probability

【问题讨论】:

  • 使用continueOutcome.append(len(list(groupby(flips)))) if len(list(groupby(flips))) &gt; Z,您当前的if 语句后跟pass 没有任何作用

标签: python if-statement for-loop probability


【解决方案1】:

我认为您的代码包含更多错误,例如您需要使用 浮点除法 而不是整数除法(适当的类型转换)和您的 条件概率 计算公式需要更正,您计算的概率实际上是z-score,假设IID变量进行了大量试验,这是修改后的代码,我认为它对您有用:

import random
from itertools import groupby
import statistics
import matplotlib.pyplot as plt
import numpy as np

# Function for biased coin
def flip(p): return 'H' if random.random() < p else 'T'

# Simulation
def simulate_three(X, N, Y, Z):
    Outcome = [] # List of results
    for i in range(X): # For loop for the X number of iterations
        flips = [flip(0.6) for j in range(N)] # For loop for N number of coin flips
        #print len(list(groupby(flips))), flips
        if len(list(groupby(flips))) > Z: # If group condition is met
           Outcome.append(len(list(groupby(flips)))) # store to list
    prob = (1.0*len(filter(lambda x:x == 6, Outcome))) / len(Outcome) # conditional probability
    expval = (1.0*sum(Outcome))/(len(Outcome)) # conditional expectation
    zscore = (Y - expval) / statistics.stdev(Outcome) # by CLT, assuming IID variables, compute the z score
    print prob
    print expval
    print zscore
    weights = (1.0*np.ones_like(Outcome))/len(Outcome)
    plt.hist(Outcome, weights=weights, facecolor='green', alpha=0.75)
    plt.xlabel('#Groups')
    plt.ylabel('Conditional Probability of Groups | (> 5 groups)')
    plt.title('Conditional Probability Distribution')
    plt.grid(True)
    plt.show()

simulate_three(1000,10,6,5)
# 0.551198257081 : this is the conditional probability
# 6.64052287582  : this is the conditional expectation
# -0.773961977708 : this is the z-score

【讨论】:

    【解决方案2】:

    python 文档中有 a great section on control flows. 简而言之,pass 用作一种占位符,而 continue 将继续进行下一次迭代。

    根据我对你描述的理解,你想要continue不是 pass。所以正确的版本应该是这样的:

        if len(list(groupby(flips))) <= Z:
            continue
        Outcome.append(len(list(groupby(flips))))
    

    一个更易读、更明确的版本可能是:

        if len(list(groupby(flips))) <= Z:
            pass
        else:
            Outcome.append(len(list(groupby(flips))))
    

    当然,最直接的版本可能是:

        if len(list(groupby(flips))) > Z:
            Outcome.append(len(list(groupby(flips))))
    

    所以在这种情况下,只有list 的长度大于Z 才会被添加到您的Outcome

    您可以通过强制 flip 函数仅返回 H 来测试这一点。如果控制流按预期工作,您将在倒数第二行抛出除以零错误。

    【讨论】:

    • 您的意思是continue 而不是pass
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-05
    相关资源
    最近更新 更多