2012-03-29 35 views
0

ファイルの入力を求められます(この場合は「histogram.txt」です)。プログラムはテキストファイル内の各スコアを取り、ファイル内のすべての成績からヒストグラムを作成し、ユーザーが各範囲の数を確認できるように整理します。私は、プログラムを実行するたびしかし、すべての20件の等級は、次のように> = 100 に記録されます簡単なpythonプログラム

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) 

:私は非常に単純なコードを書いた

100 : ******************** 
90-99 : 
80-89 : 

など ...どのように私はプログラムが正しい場所に星を置くようにしますか?

+3

常にステップ1:プログラムに入っているデータが正しいことを確認します。 –

+2

文字列と数字を比較しています... – avasal

+1

少しヒント:ヒストグラムに11種類の変数を使用する代わりに、リストを使用してインデックスを計算することができます。ヒストグラム[min(100、score)/ 10] + = 1'である。 「分」は、すべてのスコアを同じスロットに100を超える値にすることです。より一般的なデータの場合、テキスト内の単語の数をカウントするなど、辞書を使用できます。 –

答えて

2

比較する前にscoreをintに変換する必要があります。

score = int(score) # convert to int 
if score >= 100: 
    histogram10 = histogram10 + 1 
# other cases 

入力ファイルに空白行がある場合は、intに変換する前に必要なチェックを追加する必要があります。また、10種類の変数の代わりに、簡単にリストを使用することもできます。

+0

これもありがとう、アドバイスありがとうございます。私はまだcompsciで非常に新しい:Pあなたは気にしない場合は、これでリストを使用する方法を説明することができますか? –

+1

リストチュートリアルhttp://docs.python.org/tutorial/introduction.html#listsをご覧ください。 'histogram0'では' l [0] 'を使うことができます。ヒストグラム1には' l [1] 'などを使うことができます。 – taskinoor

4

ファイルから読み取られたデータは文字列です。それをint()に渡して最初に整数に変換します。

>>> int('25') 
25 
+0

本当にありがとうございました。 –

+0

答えが良かったらそれを受け入れるべきです。 –

関連する問題