<学习记录>使用Pygal 模拟掷骰子

  1. 创建一个骰子类 Die():
from random import randint


class Die:
    def __init__(self, num_sides=6):
    	# 一共六面
        self.num_sides = num_sides
   
    def roll(self):
    	# 返回1~6 中的随机一位数字
        return randint(1, self.num_sides)

2.掷骰子

from die import Die

die = Die()
results = []

for roll_num in range(100):
    result = die.roll()
    results.append(result)

print(results)

结果如下
[5, 1, 5, 1, 1, 1, 3, 4, 1, 1, 2, 2, 2, 5, 3, 5, 6, 3, 1, 6, 3, 2, 4, 5, 1, 1, 4, 1, 4, 6, 5, 3, 1, 6, 4, 1, 1, 6, 2, 1, 6, 4, 4, 5, 4, 6, 5, 4, 6, 3, 4, 2, 3, 2, 4, 4, 3, 5, 4, 6, 1, 2, 5, 5, 2, 6, 5, 4, 4, 6, 4, 4, 1, 6, 1, 1, 5, 4, 4, 6, 3, 2, 2, 3, 6, 6, 2, 3, 5, 3, 5, 1, 6, 1, 5, 3, 6, 2, 1, 6]

3.分析结果:
计算每个点出现的次数:

frequencies = []
for value in range(1, die.num_sides+1):
    frequency = results.count(value)
    frequencies.append(frequency)
print(frequencies)

结果:[152, 168, 159, 156, 182, 183]
4.绘制直方图:

# 直方图
hist = pygal.Bar()

hist.title = "Results of rolling one D6 1000 times"
hist.x_labels = ['1', '2', '3', '4', '5', '6']
hist.x_title = "Result"
hist.y_title = "Frequency of Result"
# 在图表中添加数值
hist.add('D6',frequencies)
# 渲染成SVG文件 用浏览器打开
hist.render_to_file('die_visual.svg')

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值