fork download
  1. from timeit import timeit
  2. from itertools import chain, ifilterfalse
  3. import numpy as np
  4.  
  5. m = ((2,0,2,2),(4,4,5,4),(0,9,4,8),(2,2,0,0))
  6. mm = np.array(m)
  7.  
  8. def zeroCountOP():
  9. return [item for row in m for item in row].count(0)
  10.  
  11. def zeroCountTFE():
  12. return len([item for row in m for item in row if item == 0])
  13.  
  14. def zeroCountJFS():
  15. return sum(row.count(0) for row in m)
  16.  
  17. def zeroCount():
  18. total = 0
  19. for x in ifilterfalse(bool, chain(*m)):
  20. total += 1
  21. return total
  22.  
  23. def zeroCountuser2931409():
  24. # `reduce` is in `functools` in Py3k
  25. return reduce(lambda a, b: a + b, m).count(0)
  26.  
  27. def zeroCountsmci():
  28. return (mm==0).sum()
  29.  
  30. print('Original code ', timeit(zeroCountOP, number=100000))
  31. print('@J.F.Sebastian ', timeit(zeroCountJFS, number=100000))
  32. print('@thefourtheye ', timeit(zeroCountTFE, number=100000))
  33. print('@user2931409 ', timeit(zeroCountuser2931409, number=100000))
  34. print('@frostnational ', timeit(zeroCount, number=100000))
  35. print('@smci ', timeit(zeroCountsmci, number=100000))
Success #stdin #stdout 2.62s 20656KB
stdin
Standard input is empty
stdout
('Original code     ', 0.2307131290435791)
('@J.F.Sebastian    ', 0.1814560890197754)
('@thefourtheye     ', 0.19155097007751465)
('@user2931409      ', 0.18722081184387207)
('@frostnational    ', 0.16568803787231445)
('@smci             ', 1.1832242012023926)