manxing
manxing

Reputation: 3305

ZeroDivisionError: float division` in python

querytimes = "SELECT video_id, COUNT(src_ip) FROM video GROUP BY video_id ORDER BY COUNT(src_ip) DESC"
cur.execute (querytimes)
dltimes = cur.fetchall()
for row in dltimes:

    videoid = str(row [0])
    downloadtimes = int(str(row [1]))
    x.append(rank)
    rank = rank + 1 
    y.append(downloadtimes)
    v.append(videoid)


counter = dict(zip(v, y))
for n in xrange(1, max(counter.itervalues()) + 1):
    perc = 100. / sum(1 for nb in counter.itervalues() if nb == n) / len(counter)
if perc:
   print '%.f%% videos have been downloaded %d times' % (perc, n)

This is my code. At first I read data from a database, then put videoid and downloadtimes into a dictionary, and do some calculation, but I got the following error:

perc = 100. / sum(1 for nb in counter.itervalues() if nb == n) / len(counter) ZeroDivisionError: float division

Can anyone help a bit?

Upvotes: 0

Views: 7857

Answers (2)

Óscar López
Óscar López

Reputation: 236004

Check to see if counter is empty - in other words, if the value returned in dltimes doesn't have elements. I'd do something like this inside the for loop:

if counter:
    perc = 100. / sum(1 for nb in counter.itervalues() if nb == n) / len(counter)
else:
    perc = 0

Alternatively, it's possible that there are no values where nb == n it's True. in that case:

s = sum(1 for nb in counter.itervalues() if nb == n)
if counter and s:
    perc = 100. / s / len(counter)
else:
    perc = 0

Upvotes: 0

mac
mac

Reputation: 43031

Have you checked that your counter dictionary has at least one value that matches the nb == n condition? To me it seems like either your sum or your len return 0 as a result...

Check this out:

>>> n = 3
>>> counter = {'a': 1}
>>> 100. / sum(1 for nb in counter.itervalues() if nb == n) / len(counter) 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ZeroDivisionError: float division by zero
>>> counter = {'a': 3}
>>> 100. / sum(1 for nb in counter.itervalues() if nb == n) / len(counter) 
100.0

Upvotes: 3

Related Questions