0
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?

1
  • Is that last for loop right? the if part ought to be inside the loop, otherwise it'll only execute once Commented Dec 6, 2011 at 11:41

2 Answers 2

3

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
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.