python编程从入门到实践15章练习

15-3分子运动

import matplotlib.pyplot as plt

from random_walk import RandomWalk
i = 1
while True:
    #创建一个RandomWalk实例,并将其包含的点都绘制出来
    rw = RandomWalk(50000)
    rw.fill_walk()
    plt.figure(figsize=(10,6))
    number_point = list(range(rw.num_points))
    plt.plot(rw.x_values, rw.y_values, linewidth=1)

    #隐藏坐标轴
    plt.axes().get_xaxis().set_visible(False)
    plt.axes().get_yaxis().set_visible(False)

    plt.title("Random walk", fontsize=24)
    plt.xlabel("x"+ str(i) + "direction", fontsize=14)
    plt.ylabel("y"+ str(i) + "direction", fontsize=14)
    i += 1


    plt.show()
    keep_running = input("Make another walk? (y/n): ")
    if keep_running == 'n':
        break

15-4改进的随机漫步

class RandomWalk():
    def __init__(self, num_points=5000):
        self.num_points = num_points

        self.x_values = [0]
        self.y_values = [0]

    def fill_walk(self):
        """计算随机漫步包含的所有点"""

        while len(self.x_values) < num_points:
            #决定前进方向和距离
            x_direction = choice([-1, 1])
            #x_direction = choice([1])
            x_distance = choice([0,1,2,3,4,5,6,7,8])
            x_step = x_direction * x_distance

            y_direction = choice([-1, 1])
            #y_direction = choice([1])
            y_distance = choice([0,1,2,3,4,5,6,7,8])
            y_step = y_direction * y_distance

            if x_step == 0 and y_step == 0:
                continue
            
            next_x = self.x_values[-1] + x_step
            next_y = self.y_values[-1] + y_step

            self.x_values.append(next_x)
            self.y_values.append(next_y)

15-5重构

#random_walk.py
from random import choice

class RandomWalk():
    def __init__(self, num_points=5000):
        self.num_points = num_points

        self.x_values = [0]
        self.y_values = [0]
        self.get_step()
    def fill_walk(self):
        """计算随机漫步包含的所有点"""

        while len(self.x_values) < self.num_points:
            # 决定前进方向和距离
            x_step = self.get_step()
            y_step = self.get_step()

            if x_step == 0 and y_step == 0:
                continue

            next_x = self.x_values[-1] + x_step
            next_y = self.y_values[-1] + y_step

            self.x_values.append(next_x)
            self.y_values.append(next_y)

    def get_step(self):
        # direction = choice([-1, 1])
        direction = choice([-1,1])
        distance = choice([0, 1, 2, 3, 4, 5, 6, 7, 8])
        step = direction * distance
        return step

15-6自动生成标签

"""dice_visual.py"""
import pygal
from die import Die

#创建两个D8骰子
die_1 = Die(8)
die_2 = Die(8)

#掷多次骰子,并将结果存储在列表里
results = []
for roll_num in range(1000000):
    result = die_1.roll() + die_2.roll()
    results.append(result)

frenquncies = []
max_reuslt = die_1.num_sides + die_2.num_sides
for value in range(1, max_reuslt):
    frenquncy = results.count(value)
    frenquncies.append((frenquncy))

hist = pygal.Bar()
hist.title= "Results of rolling two D8 dice 1000,000 times."

hist.x_labels = [x for x in range(2,17)]
hist.x_title = "Result"
hist.y_title = "Frequncy of Result"

hist.add("D8 + D8",frenquncies)
hist.render_to_file('dice_visual.svg')

15-7两个D8骰子

"""dice_visual.py"""
import pygal
from die import Die

#创建两个D8骰子
die_1 = Die(8)
die_2 = Die(8)

#掷多次骰子,并将结果存储在列表里
results = []
for roll_num in range(1000000):
    result = die_1.roll() + die_2.roll()
    results.append(result)

frenquncies = []
max_reuslt = die_1.num_sides + die_2.num_sides
for value in range(1, max_reuslt):
    frenquncy = results.count(value)
    frenquncies.append((frenquncy))

hist = pygal.Bar()
hist.title= "Results of rolling two D8 dice 1000,000 times."

hist.x_labels = [x for x in range(2,17)]
hist.x_title = "Result"
hist.y_title = "Frequncy of Result"

hist.add("D8 + D8",frenquncies)
hist.render_to_file('dice_visual.svg')

15-8同时掷三个骰子

import pygal
from die import Die

#创建两个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)

frenquncies = []
max_reuslt = die_1.num_sides + die_2.num_sides +die_3.num_sides
for value in range(3, max_reuslt+1):
    frenquncy = results.count(value)
    frenquncies.append((frenquncy))

hist = pygal.Bar()
hist.title= "Results of rolling two D8 dice 10,000 times."

hist.x_labels = [x for x in range(3,19)]
hist.x_title = "Result"
hist.y_title = "Frequncy of Result"

hist.add("D6 + D6",frenquncies)
hist.render_to_file('dice_visual.svg')

15-9将点数相乘

import pygal
from die import Die

#创建两个D6骰子
die_1 = Die()
die_2 = Die()

#掷多次骰子,并将结果存储在列表里
results = []
for roll_num in range(10000):
    result = die_1.roll() * die_2.roll()
    results.append(result)

frenquncies = []
max_reuslt = die_1.num_sides * die_2.num_sides
for value in range(1, max_reuslt+1):
    frenquncy = results.count(value)
    frenquncies.append((frenquncy))

hist = pygal.Bar()
hist.title= "Results of rolling two D6 dice 10,000 times."

hist.x_labels = [x for x in range(1,36)]
hist.x_title = "Result"
hist.y_title = "Frequncy of Result"

hist.add("D6 × D6",frenquncies)
hist.render_to_file('dice_visual.svg')

15-10练习本章介绍的两个库

from die import Die
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches

#创建两个D6
die_1 = Die()
die_2 = Die()

#掷骰子多次,将结果存储到一个列表中
results = []
for roll_num in range(50000):
    result = die_1.roll() + die_2.roll()
    results.append(result)

#分析结果
frequencies = []
max_results = die_1.num_sides + die_2.num_sides
for value in range(2, max_results+1):
    frequency = results.count(value)
    frequencies.append(frequency)

#可视化结果
plt.bar(range(2, max_results+1), frequencies, color='Orange', align='center', label='D6+D6')
plt.xticks(range(2, max_results+1))

plt.xlabel("Results", fontsize=8)
plt.ylabel("Frequencies", fontsize=8)

# 图例
orange_patch = mpatches.Patch(color='Orange', label='D6+D6')
plt.legend(handles=[orange_patch])

plt.show()

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值