-1

In python i need to summarize data in count_list this way (like a histogram):

"""
number | occurence
  0 | *
  1 | **
  2 | ***
  3 | **
  4 | **
  5 | *
  6 | *
  7 | **
  8 | ***
  9 | *
  10 | **
"""

But instead I get this wrong output:

"""
number | occurence
  0 | 
  1 | **
  2 |
  3 |
  4 |
  5 |
  6 | **
  7 |
  8 |
  9 |
  10 | **
"""

Here is my code:

import random
random_list = []
list_length = 20
while len(random_list) < list_length:
    random_list.append(random.randint(0,10))
count_list = [0] * 11
index = 0

while index < len(random_list):
   number = random_list[index]
    count_list[number] = count_list[number] + 1
    index = index + 1


def summerizer():
    index = 0
    print count_list
    print '"'*3
    print 'number  |  occurrence'
    while index < len(count_list):
      print '%s' %' '*(7),
      print index,#the problem is here
      print ' | ',#and here
      print '%s' %'*'*(count_list[index])
      index += 1
    print '%s'%'"'*3


summerizer()
zezollo
  • 4,606
  • 5
  • 28
  • 59

3 Answers3

1

This method uses collections.Counter:

from collections import Counter
import random

random_list = []
list_length = 20

while len(random_list) < list_length:
    random_list.append(random.randint(0,10))

c = Counter(random_list)

print('number  |  occurrence')
def summerizer(dic):
    for v,d in dic.items():
        print(v, '|', '%s'%'*'*c[v])

summerizer(dic)
jpp
  • 159,742
  • 34
  • 281
  • 339
0

Try this

import random
random_list = []
list_length = 20
while len(random_list) < list_length:
    random_list.append(random.randint(0,10))
dic={}
for i in random_list:
    dic[i]=dic.get(i,0)+1
print 'number  |  occurrence'
for i in range(0,11):
    if(i not in dic):    
        print i,"|",'%s' %'*'*(0)
    else:
        print i,"|",'%s' %'*'*(dic[i])

Out put

[9, 8, 4, 2, 5, 4, 8, 3, 5, 6, 9, 5, 3, 8, 6, 2, 10, 10, 8, 9]

number  |  occurrence
0 |
1 | 
2 | **
3 | **
4 | **
5 | ***
6 | **
7 | 
8 | ****
9 | ***
10 | **
Artier
  • 1,648
  • 2
  • 8
  • 22
0

Yes i have found the problem

It is from the ide itself !!! This was a quiz in a course on UDACITY android application and the embedded compiler inside it make this wrong answer..

Same code i tried now from pydroid application on Android also made the answer that i need without any change

Thanks for trying to help all of you

`import random
 random_list = []
 list_length = 20
 while len(random_list) < list_length:
  random_list.append(random.randint(0,10))
 count_list = [0] * 11
 index = 0

 while index < len(random_list):
  number = random_list[index]
  count_list[number] = count_list[number] + 1
  index = index + 1

def summerizer():
 index = 0
 print count_list
 print '"'*3
 print 'number  |  occurrence'
 while index < len(count_list):
  print '%s' %' '*(7),
  print index,
  print ' | ',
  print '%s' %'*'*(count_list[index])
  index += 1
 print '%s'%'"'*3

summerizer()`