15-6 自动生成标签 自动生成标签 :请修改die.py和dice_visual.py,将用来设置hist.x_labels 值的列表替换为一个自动生成这种列表的循环。如果你熟悉列表解析,可尝试将 die_visual.py和dice_visual.py中的其他for 循环也替换为列表解析。
die.py
from randomimport randint
class Die():
#标识一个骰子的类
def __init__(self,num_sides=6,num_sidess =12):
#骰子迷人为六面
self.num_sides = num_sides
self.num_sidess = num_sidess
def roll(self):
#返回一个位于1和骰子面数之间的随机值
return randint(1,self.num_sides)
def rolll(self):
#返回一个位于1和12之间的随机值
return randint(1,self.num_sidess)
die_visual.py
from dieimport Die
import pygal
#创建一个D6
die_1 = Die()
die_2 = Die()
results = []
for roll_numin range(10000):
result = die_1.roll()+die_2.rolll()
results.append(result)
print(results)
#分析结果
frequencies=[]
max_result = die_1.num_sides + die_2.num_sidess
for valuein range(2,max_result):
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 aaain range(2,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-7 两个 两个D8骰子: 骰子: 请模拟同时掷两个8面骰子1000次的结果。逐渐增加掷骰子的次数,直到系统不堪重负为止。
die.py不用改变。
die_visual.py
from dieimport Die
import pygal
#创建一个D6
die_1 = Die(8)
die_2 = Die(8)
results = []
for roll_numin 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 valuein range(2,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 aaain range(2,17):
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')