Python数据分析之掷骰子的变形题
die.py
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)
掷三个骰子
three_D6.py
from die import Die
import pygal
die_1=Die()
die_2=Die()
die_3=Die()
#掷骰子多次,并将结果储存在一个列表之中
results=[]
for roll_time in range (1000):
result=die_1.roll()+die_2.roll()+die_3.roll()
results.append(result)
#分析结果
frequencies=[]
max_result=die_1.num_sides+die_2.num_sides+die_3.num_sides
for value in range (3,max_result+1):
frequency=results.count(value)
frequencies.append(frequency)
#可视化结果
hist=pygal.Bar()
hist.title="Results of rolling Three D6 1000 times."
hist.x_labels=['3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18']
hist.x_title="Result"
hist.y_title="Frequency of Result"
hist.add('D6+D6+D6',frequencies)
hist.render_to_file('three_D6.svg')
可视化结果如下所示:
掷两个骰子并将所得点数相乘
Two_multi.py
from die import Die
import pygal
#引入两个六面的骰子
die_1=Die()
die_2=Die()
#计算两个骰子相乘的结果
results=[]
for roll_time in range (10000):
result=die_1.roll()*die_2.roll()
results.append(result)
#计算两个骰子相乘出现的各种结果的频率
frequencies=[]
for value in[1,2,3,4,5,6,8,10,12,15,18,24,25,30]:
frequency=results.count(value)
frequencies.append(frequency)
#可视化结果
hist=pygal.Bar()
hist.titile="the results of two D6 multiple"
hist.x_labels=['1','2','3','4','5','6','8','10','12','15','18','24','25','30']# 横坐标显示的数值
hist.x_title="Results"
hist.y_title="Frequencies of result"
hist.add('D6*D6',frequencies)
hist.render_to_file('Two_multi.svg')
可视化结果如下所示:
Python 学习之数据分析