计算实验抛头的概率

问题描述

我想通过随机生成 0s 或 1s 并为 0 分配 'h' 和为 1 到 n 分配 't' 来计算掷硬币正面的实验概率。翻转次数为 100。

import random

array_ht = []

flip_count = 0

while flip_count != 100:
    n = random.randint(0,1)
    if n == 0:
        n = "h"
    elif n == 1:
        n = "t"
    flip_count += 1
    array_ht.append(n)

for x in array_ht:
    h_count = 0
    if x == "h":
        h_count += 1

    print(h_count + "%")

for 循环遍历 array_ht 的每个对象,如果找到“h”,则将头部翻转次数加 1。但是代码不起作用,只是打印“1% 0% 1% 0% 0% ...”

实际发生的情况是,例如,如果生成的序列是 '0,1,1' 那么 array_ht = [h,t,h,t] 打印的概率为 (4/9*100=) 44.444444%。

实际上我们不需要为 n 分配 'h' 或 't',我们可以只查找 0 的数量,但之前我也想打印 array_ht。

解决方法

这有帮助吗?这会以 h 百分比格式计算 t% 的概率。

解释:

import random

tosses = []

# Getting A List With 100,0s and 1s in it
for i in range(100):
    tosses.append(random.randint(0,1))

# Indexing Every 0 for a `h` and every 1 for a `t`
for i in range(len(tosses)):
    if tosses[i] == 0:
        tosses[i] = "h"
    else:
        tosses[i] = "t"

# Getting Count Of How Many Times Heads Or Tails Was In The List
freq_h = tosses.count('h')
freq_t = tosses.count('t')


# Calculating The Probablity (freq/total_outcomes) (x100 optional if want to calculate in percentage use x100)
prob_h = (freq_h/len(tosses))*100
prob_t = (freq_t/len(tosses))*100

# Adding A `%` sign to the numbers and round them up
percent_h = str(round(prob_h)) + "%"
percent_t = str(round(prob_t)) + "%"

# The Final Result
print("Probablity Heads:",percent_h)
print("Probablity Tails:",percent_t)

编辑:以前解决方案的一个大大缩短的版本(快速和肮脏)

import random
tosses = []
for i in range(100):
    tosses.append(random.randint(0,1))
for i in range(len(tosses)):
    if tosses[i] == 0:
        tosses[i] = "h"
    else:
        tosses[i] = "t" 

print("Probablity Heads:",str(round((tosses.count('h')/len(tosses))*100)) + "%")
print("Probablity Tails:",str(round((tosses.count('t')/len(tosses))*100)) + "%")
,

您的代码打印 1% 0% 1% 1% 的原因是,您在 for 循环中放置了 print 语句和 h_count 变量,因此每次迭代 array_ht 时它都会重新初始化{1}}

for x in array_ht:
    h_count = 0
    if x == "h":
        h_count += 1

    print(h_count + "%")

因此,如果您对程序进行了试运行,它的作用如下:

array_ht 取一个元素,然后将 h_count 初始化为 0 如果元素 = "h",它会将 1 添加到您的 h_count

然后它打印 h_count 一次迭代结束,返回开始,

array_ht中的下一个元素并将h_count重新初始化为0 然后又是同样的事情

这是我制作的一个版本:

import random

def toss(num):
    array = [random.randint(0,1) for x in range(num)]
    return array.count(0),array.count(1)


outcomes = toss(1000)
heads = outcomes[0]
tails = outcomes[1]

print(f"Probability of Heads: {heads/sum(outcomes)*100}%")
print(f"Probability of Tails: {tails/sum(outcomes)*100}%")
,

您的问题的简单解决方案是将 h_count = 0 移出 for 循环。但除此之外,您的整个代码还可以简化:

import random

tosses = ["ht"[random.randint(0,1)] for i in range(100)] # we can use string indexing to convert "h" and "t" to 0 an 1,respectively.

print(f"{(tosses.count('h') / len(tosses)) * 100}%")