微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

绘制与掷骰子次数相对应的海龟直方图

如何解决绘制与掷骰子次数相对应的海龟直方图

我对 python 还很陌生,所以请多多包涵。我正在尝试制作一个海龟直方图,它计算各种数字出现 100 卷 3 个骰子的次数。但是在计算了直方图的最大高度和我从掷骰子的试验中得到的总高度后,直方图与我预期的完全不同。我当前的直方图输出和预期的直方图附在下面。 #注意输出不断变化,因为它有 randrange 提前致谢。

当前代码

from random import randrange
import turtle

totals = dict()
for i in range(3,19):
    totals[i] = 0
    
# Todo: Set a variable called trials here so we can loop 100 times
trials = 100
for i in range(trials):
     first_roll = randrange(1,7)
     second_roll = randrange(1,7)
     third_roll = randrange(1,7)
     total = first_roll + second_roll + third_roll
     print(total)
     totals[total] += 1


maxheight = 0
for i in range(3,19):
    print(i,totals[i])
    if totals[i] > maxheight:
        maxheight = totals[i]
scr = turtle.Screen()
t = turtle.Turtle()

t.penup()
t.goto(-138,-175)
t.pendown()

for i in range(3,19):
    t.write(i,align="center")
    t.forward(20)

t.penup()
t.goto(-150,19):
    height = int(totals[i] * 300 / maxheight)
    t.forward(height)
    t.right(90)
    t.forward(20)
    t.backward(height)
# Todo: In the end,draw the line at the bottom of our histogram

scr.exitonclick()

电流输出

enter image description here

预期输出

enter image description here

解决方法

你的问题是这个代码:

for i in range(3,19):
    height = int(totals[i] * 300 / maxheight)
    t.forward(height)
    t.right(90)
    t.forward(20)
    t.backward(height)

它没有考虑到海龟当前的方向,也没有让海龟保持一个合理的方向。考虑一下:

for i in range(3,19):
    height = int(totals[i] * 300 / maxheight)

    turtle.left(90)
    turtle.forward(height)
    turtle.right(90)
    turtle.forward(20)
    turtle.right(90)
    turtle.forward(height)
    turtle.left(90)

假设海龟在开始时面向 0 度,而让海龟面向 0 度。带有额外调整的完整代码:

from random import randrange
from turtle import Screen,Turtle

TRIALS = 100
COLUMN_WIDTH = 20

totals = dict()

for i in range(3,19):
    totals[i] = 0

for _ in range(TRIALS):
    first_roll = randrange(1,7)
    second_roll = randrange(1,7)
    third_roll = randrange(1,7)
    total = first_roll + second_roll + third_roll
    totals[total] += 1

maxheight = 0

for i in range(3,19):
    if totals[i] > maxheight:
        maxheight = totals[i]

screen = Screen()
turtle = Turtle()

turtle.penup()
turtle.goto(-160 - COLUMN_WIDTH/2,-175)
turtle.pendown()

turtle.forward(COLUMN_WIDTH)

for i in range(3,19):
    turtle.write(i,align="center")
    turtle.forward(COLUMN_WIDTH)

turtle.penup()
turtle.goto(-160,-175)
turtle.pendown()

for i in range(3,19):
    height = int(totals[i] * 300 / maxheight)

    turtle.left(90)
    turtle.forward(height)
    turtle.right(90)
    turtle.forward(COLUMN_WIDTH)
    turtle.right(90)
    turtle.forward(height)
    turtle.left(90)

turtle.hideturtle()
screen.exitonclick()

enter image description here

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。