python编程题概率-Python3根据基础概率随机生成选项

想要实现一个功能:不同事件发生的基础概率不同,根据基础概率来随机生成选项。

比如,北京的秋天有四种状态,并分别对应一个基础概率,然后随机生成某一天的天气情况。

weatherlist = ["Sunny", "Cloudy", "Windy", "Rainy"]

probaslist = [0.30, 0.35, 0.25, 0.1]

实现脚本如下:

import random

def generate_weather(weather_list, probabilities_list):

if not (0.99999 < sum(probabilities_list) < 1.00001):

raise ValueError("The probabilities are not normalized!")

if len(weather_list) != len(probabilities_list):

raise ValueError("The length of two input lists are not match!")

random_normalized_num = random.random() # random() -> x in the interval [0, 1).

accumulated_probability = 0.0

for item in zip(weather_list, probabilities_list):

accumulated_probability += item[1]

if random_normalized_num < accumulated_probability:

return item[0]

测试运行情况:

weatherlist = ["Sunny", "Cloudy", "Windy", "Rainy"]

probaslist = [0.30, 0.35, 0.25, 0.1]

output_dict = {}

for x in weatherlist:

output_dict.update({x: 0})

n = 10000

for i in range(n):

weather = generate_weather(weatherlist, probaslist)

output_dict[weather] += 1

percentage_dict = {key: output_dict[key]/n for key in output_dict}

print(output_dict)

print(percentage_dict)

得到的结果为:

{"Sunny": 3033, "Cloudy": 3466, "Windy": 2484, "Rainy": 1017}

{"Sunny": 0.3033, "Cloudy": 0.3466, "Windy": 0.2484, "Rainy": 0.1017}

模拟生成10000次天气情况,将各种天气情况的频率与初始设置的基础概率比较,发现结果很吻合。

巨人的肩膀:

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值