谏言:穷则独善其身,达则兼济天下
# 绘制直方图 # die.py import pygal from random import randint class Die(): """表示一个骰子的类""" def __init__(self,num_sides=6): self.num_sides=num_sides def roll(self): """返回一个位于1和骰子面数之间的随机值""" return randint(1,self.num_sides) # die_visual.py # from die import Die die=Die() # 掷几次骰子,并将结果存储在一个列表中 results=[] for roll_num in range(1000): result =die.roll() results.append(result) frequencies=[] # 分析结果可视化 frequencies=[] for value in range(1,die.num_sides+1): frequency= results.count(value) frequencies.append(frequency) # 对结果进行可视化 hist =pygal.Bar() hist.title = "投掷骰子每个点出现的次数" hist.x_labels=[‘1‘,‘2‘,‘3‘,‘4‘,‘5‘,‘6‘] hist.x_title = "Result" hist.y_title = "Frequencies of Result" hist.add(‘D06‘,frequencies) hist.render_to_file(‘die_visual.svg‘)
import pygal from random import randint class Die(): """表示一个骰子的类""" def __init__(self,num_sides=6): self.num_sides=num_sides def roll(self): """返回一个位于1和骰子面数之间的随机值""" return randint(1,self.num_sides) # die_visual.py # from die import Die # 创建两个D6骰子 die_1=Die() die_2=Die() # 掷几次骰子,并将结果存储在一个列表中 results=[] for roll_num in range(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(2,max_result+1): frequency= results.count(value) frequencies.append(frequency) # 对结果进行可视化 hist =pygal.Bar() hist.title = "投掷两个骰子之和每个点出现的次数" hist.x_labels=[‘2‘,‘3‘,‘4‘,‘5‘,‘6‘,‘7‘,‘8‘,‘9‘,‘10‘,‘11‘,‘12‘] hist.x_title = "Result" hist.y_title = "Frequencies of Result" hist.add(‘D6+D6‘,frequencies) hist.render_to_file(‘die_visual_2.svg‘)
import pygal from random import randint class Die(): """表示一个骰子的类""" def __init__(self,num_sides=6): self.num_sides=num_sides def roll(self): """返回一个位于1和骰子面数之间的随机值""" return randint(1,self.num_sides) # die_visual.py # from die import Die # 创建一个D6骰子和一个D10 die_1=Die() die_2=Die(10) # 掷几次骰子,并将结果存储在一个列表中 results=[] for roll_num in range(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 = "投掷一个6面骰子和一个10面骰子50000次之和每个点出现的次数" hist.x_labels=[‘2‘,‘3‘,‘4‘,‘5‘,‘6‘,‘7‘,‘8‘,‘9‘,‘10‘,‘11‘,‘12‘,‘13‘,‘14‘,‘15‘,‘16‘] hist.x_title = "Result" hist.y_title = "Frequencies of Result" hist.add(‘D6+D10‘,frequencies) hist.render_to_file(‘die_visual_3.svg‘)
原文:https://www.cnblogs.com/python-study-notebook/p/12770812.html