Частотная гистограмма, для цикла - PullRequest
0 голосов
/ 17 октября 2018

так что я сразу перейду к делу.Я пытаюсь создать гистограмму, которая берет числа из текстового документа и делает частотную гистограмму (0-10).Я могу заставить это работать, если я не использую цикл for, но это очень неэффективно.Вот что у меня сейчас есть:

from graphics import *
import math

def main():

 #saying what the program does
 print("This is a program that reads a test file of test scores (0-10)")
 print("and draws a histogram with the amount of students with that score")
 print("raising the bar by one for each student.")

 #Get the name of the files with the scores
 fileInput = input("Enter the file name with the scores: ")

 #open the file with the scores and read the first line to get the # of students
 infile = open(fileInput, "r")
 stuNum = int(infile.readline())
 lineRead = infile.readlines()

 #Creates a window using the amount of students to base the height
 win = GraphWin("These Students Failed", 400, 400)
 win.setCoords(0,0,100,20)

 #Create list to hold number of each score
 scoreList = [0,0,0,0,0,0,0,0,0,0,0]

 #Create loop for each line in the file
 for line in lineRead:
     line = int(line)
     scoreList[line] += 1

 #create initial bar  
 x = 0
 height = scoreList[x]
 bar = Rectangle(Point(0,0),Point(15, height))
 bar.setFill("green")
 bar.setWidth(2)
 bar.draw(win)


 #create loop for drawing bars  
 for i in range(10):
     height = scoreList[x+1]
     bar = Rectangle(Point((15*x),0), Point((15*x), height))
     bar.setFill("green")
     bar.setWidth(2)
     bar.draw(win)


 main()

Итак, все работает, кроме цикла for.Кроме того, я пытаюсь сделать это без дополнительного импорта (кроме математики и графики).

Вот как выглядит текстовый документ, из которого я получаю цифры:

Текстовый документ

Таким образом, высота каждого столбца - это суммараз число встречается.

Спасибо!

1 Ответ

0 голосов
/ 17 октября 2018
#Create initial bar for students who got zero
x = 0
y = 15
height = scoreList[x]
bar = Rectangle(Point(0,0),Point(15, height))
bar.setFill("green")
bar.setWidth(2)
bar.draw(win)


#create loop for drawing bars  
for i in range(11):

    #store x as itself +1 so it goes up 1 each loop
    x = x + 1

    #have y as iteself +15 so it goes up 15 each loop
    y = y + 15

    #the height is equal to however many times the number occured in scoreList
    height = scoreList[x]

    #Create the bar based off of the first bar and the height
    bar = Rectangle(Point(y-15,0), Point((y), height))

    bar.setFill("green")
    bar.setWidth(2)
    bar.draw(win)

Есть мой новый цикл, который печатает их просто отлично, но я получаю индекс вне диапазона ошибок для height = scoreList[x], но, похоже, это не влияет на программу.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...