Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing a histogram

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?

like image 311
George Burrows Avatar asked Mar 26 '26 09:03

George Burrows


1 Answers

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.

like image 73
Raymond Hettinger Avatar answered Mar 28 '26 22:03

Raymond Hettinger



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!