1. 安装Pygal
pip3 install --user pygal
2. 使用Pygal模拟掷骰子
- 定义骰子类
from random import randint
class Die():
"""表示一个骰子的类"""
def __init__(self, num_sides=6):
"""骰子默认为6面"""
self.num_sides = num_sides
def roll(self):
"""返回一个位于1和骰子面数之间的随机值"""
return randint(1,self.num_sides)
pass
- 随机掷100次
from die import Die
#创建一个D6
die = Die()
#掷几次骰子,并将结果存储在一个列表中
results = []
for roll_num in range(1,100):
result = die.roll()
results.append(result)
print(results)
- 分析结果
from die import Die
#创建一个D6
die = Die()
#掷几次骰子,并将结果存储在一个列表中
results = []
for roll_num in range(1,1000):
result = die.roll()
results.append(result)
#分析结果
frequencies = []
for value in range(1,die.num_sides+1):
frequency = results.count(value)
frequencies.append(frequency)
print(frequencies)
- 使用pygal将结果绘制成直方图
from die import Die
import pygal
#创建一个D6
die = Die()
#掷几次骰子,并将结果存储在一个列表中
results = []
for roll_num in range(1,1000):
result = die.roll()
results.append(result)
#分析结果
frequencies = []
for value in range(1,die.num_sides+1):
frequency = results.count(value)
frequencies.append(frequency)
#对结果进行可视化
hist = pygal.Bar()
hist.x_labels = ['1','2','3','4','5','6']
hist.x_title = "results"
hist.y_title = "frequency for Result"
hist.add('D6',frequencies)
hist.render_to_file('die_visual.svg')
print(frequencies)
生成svg文件使用浏览器打开
image
- 同时掷俩个骰子结果分析
from die import Die
import pygal
#创建一个D6
die_1 = Die()
die_2 = Die()
#掷几次骰子,并将结果存储在一个列表中
results = []
for roll_num in range(1,1000):
result = die_1.roll()+die_2.roll()
results.append(result)
#分析结果
frequencies = []
max_result = die_1.num_sides+die_2.num_sides
for value in range(1,max_result+1):
frequency = results.count(value)
frequencies.append(frequency)
#对结果进行可视化
hist = pygal.Bar()
hist.title="Results of rolling two D6 dice 1000 times"
hist.x_labels = ['2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12']
hist.x_title = "results"
hist.y_title = "frequency for Result"
hist.add('D6+D6',frequencies)
hist.render_to_file('die_visual.svg')
image
- 同时掷俩个不同面数的骰子
from die import Die
import pygal
#创建一个D6
die_1 = Die()
die_2 = Die(10)
#掷几次骰子,并将结果存储在一个列表中
results = []
for roll_num in range(1,50000):
result = die_1.roll()+die_2.roll()
results.append(result)
#分析结果
frequencies = []
max_result = die_1.num_sides+die_2.num_sides
for value in range(2,max_result+1):
frequency = results.count(value)
frequencies.append(frequency)
#对结果进行可视化
hist = pygal.Bar()
hist.title="Results of rolling two D6 dice 50000 times"
hist.x_labels = ['2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12','13','14','15','16']
hist.x_title = "results"
hist.y_title = "frequency for Result"
hist.add('D6+D6',frequencies)
hist.render_to_file('die_visual.svg')
image
网友评论