``````class Database(Student):
def __init__(self):
g = []
choice = ['Basketball','Football','Other','Baseball','Handball','Soccer','Volleyball','I do not like sport']
data = student.sport
k = len(student.fname)
print k
freq = {}
for i in data:
freq[i] = freq.get(i, 0) + 1
for i in choice:
if i not in freq:
freq[i] = 0
for i in freq:
print i, freq[i]``````

I want to calculate each frequency in percentage. I tried to use freq / k but all returned 0 0 0 0 0 0

How do I calculate each frequency?

'student' has not been declared so who knows what this does.

``````data = student.sport
k = len(student.fname)``````

``````for i in data:
freq[i] = freq.get(i, 0) + 1``````

Your code is poor at best. Add some print statements, print the dictionary after each add, or do whatever to test it as you go along to make sure that you have something to calculate.

Hi, thanks for the reply. student is a class. It is a huge program so I cannot post the entire thing here. But everything works fine - no error except the fact that I cannot caclulate the percentage

according to the code above
if I do

freq / k this will return plain ZERO
k in this case is a number and freq is a value assigned to each key in dictionary freq

freq / k this will return plain ZERO

If it is less than one then it is being rounded to zero because divide defaults to integers in Python 2.X, so convert to float
float(freq) / k
and see if that makes a difference. If not, post some test data as well.

below is the complete code

``````import csv
class Student(object):
'''class to represent a person'''
def __init__(self, lname, fname, ID, sport):
self.lname = lname
self.fname = fname
self.ID = ID
self.sport = sport
student = [Student(row[0], row[1], row[2], row[3]) for row in reader][1::]
print "%-14s|%-10s|%-5s|%-11s" %('First Name','Last Name','ID','Favorite Sport')
print "-" * 45
for i in range(len(student)):
print "%-14s|%-10s|%-5s|%3s" %(student[i].lname,student[i].fname,student[i].ID,student[i].sport)

choice = ['Basketball','Football','Other','Baseball','Handball','Soccer','Volleyball','I do not like sport']
lst = []
k = len(student)
# 23
h=0
for i in range(len(student)):
lst.append(student[i].sport)
for a in set(lst):
print lst.count(a)
h = lst.count(a)
print "Percentage",(h / k) * 100``````

I am going to post the last section - the percentage output

4
Percentage 0
1
Percentage 0
6
Percentage 0
1
Percentage 0
3
Percentage 0
8
Percentage 0

You aren't converting to a float. Try this code to emphasize the point.

``````h_list = [ 1, 2, 3 ]
k_list = [ 2, 3, 4 ]
for h in h_list:
for k in k_list:
print h,k, (h/k) * 100, "----->", float(h)/k``````

I tried float in the end. But float worked here

``h = float(lst.count(a))``

Thank you.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.