Reputation:
I have been trying to make a histogram using the data given in survey
below.
#represents the "information" (the summarized data)
ranking = [0,0,0,0,0,0,0,0,0,0,0]
survey = [1,5,3,4,1,1,1,2,1,2,1,3,4,5,1,7]
for i in range(len(survey)):
ranking[survey[i]]+=1
#create histogram
print("\nCreating a histogram from values: ")
print("%3s %5s %7s"%("Element", "Value", "Histogram"))
for i in range(len(ranking)):
print("%7d %5d %-s"%(i+1, ranking[i+1], "*" * ranking[i+1]))
Here is exactly what the shell displays when I run my code:
Creating a histogram from values:
Element Value Histogram
1 7 *******
2 2 **
3 2 **
4 2 **
5 2 **
6 0
7 1 *
8 0
9 0
10 0
Traceback (most recent call last):
File "C:\folder\file23.py", line 17, in <module>
print("%7d %5d %-s"%(i+1, ranking[i+1], "*" * ranking[i+1]))
IndexError: list index out of range
My expected output is the above thing just without the traceback.
The shell is displaying the right thing, I'm just unsure of the error message. How can I fix this?
Upvotes: 0
Views: 469
Reputation: 881477
When i
reaches its highest value, len(ranking) - 1
, your use of ranking[i+1]
is clearly "out of range"! Use range(len(ranking) - 1
in the for
loop to avoid the error.
The counting can be simplified, too:
import collections
ranking = collections.Counter(survey)
for i in range(min(ranking), max(ranking)+1):
print("%7d %5d %-s"%(i, ranking[i], "*" * ranking[i]))
Here you need min
and max
because Counter
is mapping-like, not sequence-like. But it will still work fine (and you can use range(0, max(ranking)+1)
if you prefer!-)
Upvotes: 1
Reputation: 43126
Your index i
is incremented up to len(ranking)-1
, which is the last valid index in ranking
, but you're trying to access ranking[i+1]
, hence the IndexError
.
Fix:
for i in range(len(ranking)-1):
Upvotes: 0