fork download
  1. from timeit import timeit
  2. from itertools import chain, filterfalse
  3. import functools
  4.  
  5. m = ((2,0,2,2),(4,4,5,4),(0,9,4,8),(2,2,0,0))
  6.  
  7. def zeroCountOP():
  8. return [item for row in m for item in row].count(0)
  9.  
  10. def zeroCountTFE():
  11. return len([item for row in m for item in row if item == 0])
  12.  
  13. def zeroCountJFS():
  14. return sum(row.count(0) for row in m)
  15.  
  16. def zeroCount():
  17. total = 0
  18. for x in filterfalse(bool, chain(*m)):
  19. total += 1
  20. return total
  21. def zeroCountuser2931409():
  22. # `reduce` is in `functools` in Py3k
  23. return functools.reduce(lambda a, b: a + b, m).count(0)
  24.  
  25. print('Original code ', timeit(zeroCountOP, number=100000))
  26. print('@J.F.Sebastian ', timeit(zeroCountJFS, number=100000))
  27. print('@thefourtheye ', timeit(zeroCountTFE, number=100000))
  28. print('@user2931409 ', timeit(zeroCountuser2931409, number=100000))
  29. print('@frostnational ', timeit(zeroCount, number=100000))
Success #stdin #stdout 1.21s 10104KB
stdin
Standard input is empty
stdout
Original code      0.27121400833129883
@J.F.Sebastian     0.19829607009887695
@thefourtheye      0.2541079521179199
@user2931409       0.20377111434936523
@frostnational     0.18228411674499512