Printing a histogram
Question
I have a list of integer percentages which I need to print using the following pattern:
The index of a value, a tab (8 spaces), a '*' printed for each percentage point
also if the value for an index is 0, print 'less than 1 percent'
I have tried this code:
for b in new_tally:
if b > 0:
print new_tally[b], \t, '*' * b
else:
print 'Less than 1% of words had this length'
However I keep getting the error code: list index out of range.
I do not understand this at all, can someone point out what I have done wrong?
Solution
I think the code you wanted was:
>>> new_tally = [5, 7, 8, 6, 4, 2]
>>> for i, b in enumerate(new_tally, 1):
print i, ':', b, '*' * b
1 : 5 *****
2 : 7 *******
3 : 8 ********
4 : 6 ******
5 : 4 ****
6 : 2 **
The cause of the original traceback is that list members are looked up using square brackets instead of parentheses. new_tally(i)
is a function call. new_tally[i]
is an indexed lookup.
OTHER TIPS
for key,val in new_tally.iteritems():
print('{k} {a}'.format(k=key,a='*'*int(val)))
or, if you want the histogram sorted in descending order of frequency:
import operator
for key,val in sorted(new_tally.items(),key=operator.itemgetter(1),reverse=True):
print('{k} {a}'.format(k=key,a='*'*int(val)))
first piece:
new_tally = [5, 7, 8, 6, 4, 2]
for b in new_tally:
print b
second piece:
new_tally = [5, 7, 8, 6, 4, 2]
for i in range(len(new_tally)):
print i, new_tally[i]
the above two do approximately the same thing. you are mixing up between visiting elements in sequence (first approach) versus accessing list elements by sequential index (second approach).