Der Benutzer wird zur Eingabe einer Datei aufgefordert, in diesem Fall "histogram.txt". Das Programm nimmt jedes Ergebnis in der Textdatei und erstellt ein Histogramm aus allen Noten in der Datei, wobei sie so organisiert werden, dass der Benutzer sehen kann, wie viele von jedem Bereich es gibt. Ich schrieb einen sehr einfachen Code aus:Einfaches Python-Programm
filename = raw_input('Enter filename of grades: ')
histogram10 = 0
histogram9 = 0
histogram8 = 0
histogram7 = 0
histogram6 = 0
histogram5 = 0
histogram4 = 0
histogram3 = 0
histogram2 = 0
histogram1 = 0
histogram0 = 0
for score in open(filename):
if score >= 100:
histogram10 = histogram10 + 1
elif score >= 90:
histogram9 = histogram9 + 1
elif score >= 80:
histogram8 = histogram8 + 1
elif score >= 70:
histogram7 = histogram7 + 1
elif score >= 60:
histogram6 = histogram6 + 1
elif score >= 50:
histogram5 = histogram5 + 1
elif score >= 40:
histogram4 = histogram4 + 1
elif score >= 30:
histogram3 = histogram3 + 1
elif score >= 20:
histogram2 = histogram2 + 1
elif score >= 10:
histogram1 = histogram1 + 1
elif score >= 0:
histogram0 = histogram0 + 1
print
print 'Grade Distribution'
print '------------------'
print '100 :',('*' * histogram10)
print '90 - 99 :',('*' * histogram9)
print '80 - 89 :',('*' * histogram8)
print '70 - 79 :',('*' * histogram7)
print '60 - 69 :',('*' * histogram6)
print '50 - 59 :',('*' * histogram5)
print '40 - 49 :',('*' * histogram4)
print '30 - 39 :',('*' * histogram3)
print '20 - 29 :',('*' * histogram2)
print '10 - 19 :',('*' * histogram1)
print '00 - 09 :',('*' * histogram0)
aber wenn ich das Programm ausführen, alle zwanzig Sorten auf die> = 100 wie diese aufgezeichnet erhalten:
100 : ********************
90-99 :
80-89 :
usw. ... Wie mache ich es so, dass das Programm die Sterne an die richtigen Stellen bringt?
Immer Schritt 1: Stellen Sie sicher, dass die Daten, die in das Programm gelangen, korrekt sind. –
Sie vergleichen Zeichenfolge mit Zahlen ... – avasal
Ein kleiner Tipp: Anstatt 11 verschiedene Variablen für das Histogramm haben, könnten Sie eine Liste verwenden und den Index, z. 'Histogramm [min (100, score)/10] + = 1 '. Die 'min' ist es, alle Punkte über 100 im selben Slot zu setzen. Für allgemeinere Daten, z. B. das Zählen der Anzahl der Wörter in einem Text, könnten Sie ein Wörterbuch verwenden. –