2018-12-27

15-8 同时掷三个骰子:
同时掷三个D6骰子,可能得到的最小点数为3,而最大点数为18。请通过可视化展示同时掷三个D6骰子的结果。
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)

die_visual.py

from die import Die
import pygal
#创建一个D6
die_1 = Die()
die_2 = Die()
die_3 = Die()

results = []
for roll_num in range(10000):
    result = die_1.roll()+die_2.roll()+die_3.roll()
    results.append(result)
print(results)
#分析结果
frequencies=[]
max_result = die_1.num_sides + die_2.num_sides+die_3.num_sides
for value in range(3,max_result+1):
    frequenciey = results.count(value)
    frequencies.append(frequenciey)
print(frequencies)
#对结果可视化
hist = pygal.Bar()
hist.title = "Results of rolling one D6 1000 times."
hist.x_labels = []
for aaa in range(3,19):
    apws = aaa
    hist.x_labels.append(apws)
hist.x_title = "Resultaaaa"
hist.y_title = "Frequency of Resultbbbb"

hist.add('D6666',frequencies)
hist.render_to_file('die_visual.svg')

15-9 将点数相乘 将点数相乘 :同时掷两个骰子时,通常将它们的点数相加。请通过可视化展示将两个骰子的点数相乘的结果。
答案:
die.py不变

die_visual.py

from die import Die
import pygal
#创建一个D6
die_1 = Die()
die_2 = Die()

results = []
for roll_num in range(10000):
    result = die_1.roll()*die_2.roll()
    results.append(result)
print(results)
#分析结果
frequencies=[]
max_result = die_1.num_sides * die_2.num_sides
for value in range(1,max_result+1):
    frequenciey = results.count(value)
    frequencies.append(frequenciey)
print(frequencies)
#对结果可视化
hist = pygal.Bar()
hist.title = "Results of rolling one D6 1000 times."
hist.x_labels = []
for aaa in range(1,37):
    apws = aaa
    hist.x_labels.append(apws)
hist.x_title = "Resultaaaa"
hist.y_title = "Frequency of Resultbbbb"

hist.add('D6666',frequencies)
hist.render_to_file('die_visual.svg')

15-10 练习使用本章介绍的两个库 练习使用本章介绍的两个库 :尝试使用matplotlib通过可视化来模拟掷骰子的情况,并尝试使用Pygal通过可视化来模拟随机漫步的情况
问题一
die.py不变
die_visual.py

import matplotlib.pyplot as plt
from die import Die

die_1 = Die()
die_2 = Die()
results = []

for roll_num in range(1000):
    result = die_1.roll() + die_2.roll()
    results.append(result)
print(results)
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)
print(frequencies)
plt.plot(list(range(1, max_result + 1)), frequencies, linewidth=2)
plt.title("Result of rolling me D6 1000 times.")
plt.xlabel("Result", fontsize=14)
plt.ylabel("Square of D6 1000 times")
plt.show()

问题二

你可能感兴趣的:(2018-12-27)