[Python编程:从入门到实践] 第十五章:生成数据 习题答案

Python 小白提交答案,有不足请老鸟们指点,谢谢~

15-8 同时投掷三个骰子:如果你同时掷三个D6骰子,可能得到的最小点数为3,而最大点数为18,。请通过可视化展示同时掷三个D6骰子的结果

"""我编了一个任意数量任意面骰子投掷结果相加的程序"""

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import pygal
from die import Die15

# 創造N個骰子實例
die_sides = [8, 8,8]
dice = []
for die_side in die_sides:
    die = Die15(die_side)
    dice.append(die)
roll_results = []
# 投指定次數
roll_times = 10000
for roll_num in range(roll_times):
    roll_result = 0
    for die in dice:
        roll_result += die.roll()
    roll_results.append(roll_result)
# print(results)
max_result = 0
min_result = len(dice)
for die in dice:
    max_result += die.num_sides
# 統計結果
frequencies = []
for value in range(min_result, max_result + 1):
    frequency = roll_results.count(value)
    frequencies.append(frequency)
# print(frequencies)

# 對結果可視化
hist = pygal.Bar()
str_dice = ''
for die in dice:
    str_dice = str_dice + ' D' + str(die.num_sides)
    hist.title = "Result of rolling " + \
        str(len(dice)) + " dice of " + str_dice + " on %d times" % roll_times
hist.x_labels = [x for x in range(min_result, max_result + 1)]
hist.x_title = "Result"
hist.y_title = "Frequency of Result"
hist.add('Die', frequencies)
hist.render_to_file('n_dice_visual.svg')

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

"""我编了一个任意数量任意面骰子投掷结果相乘的程序"""

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import pygal
from die import Die15
from collections import Counter

# 創造N個骰子實例
die_sides = [6, 6, 6]
dice = [Die15(die_side) for die_side in die_sides]
roll_results = []

# 投指定次數
roll_times = 10000
for roll_num in range(roll_times):
    roll_result = 1
    for die in dice:
        roll_result *= die.roll()
    roll_results.append(roll_result)

# 计算投掷结果的范围
max_result = 1
min_result = 1
for die in dice:
    max_result *= die.num_sides

# 用dict統計結果
frequencies = {}
values = list(range(min_result, max_result + 1))
for value in values:
    frequencies[value] = roll_results.count(value)

# 删除概率为0的结果,即删除不可能的投掷结果
del_keys = []
for k, v in frequencies.items():
    if v == 0:
        del_keys.append(k)
for del_key in del_keys:
    del frequencies[del_key]

# 對結果可視化
hist = pygal.Bar()
str_dice = ''
for die in dice:
    str_dice = str_dice + ' D' + str(die.num_sides)
    hist.title = "Result of rolling " + \
        str(len(dice)) + " dice of " + str_dice + " on %d times" % roll_times
hist.x_labels = [x for x in sorted(frequencies.keys())]
hist.x_title = "Result"
hist.y_title = "Frequency of Result"
hist.add('Die', frequencies.values())
hist.render_to_file('n_dice_plus_visual.svg')


你可能感兴趣的:([Python编程:从入门到实践] 第十五章:生成数据 习题答案)