memory management - Python: What is the most optimised way to count number of 0's from a list of 0's and 1's without using any in-build functions? -


well, went interview , guy asked me question.

what optimised way count number of 0's list of 0's , 1's without using in-build functions? (python)  

i guess meant in terms of memory management well.

i wasn't sure answer these 2 things coming mind.

first, python in-build functional called count. example = [1,1,0,0,1,0,1,0,0,0,1] print a.count(0) 

but, without using in-build function , next thing coming mind loop.

counter = 0 zeros in a:     if zeros == 0:         counter = counter + 1 print counter 

this give answer , without using in-build function don't think optimised way of doing looping on list again , again.

could me out explanation? thanks

for it's worth, did few timings.

import timeit  setup1 = ''' = [1,1,0,0,1,0,1,0,0,0,1]*10 def count0(lst):     c = 0     x in lst:         if x == 0:             c += 1     return c '''  setup2 = ''' = [1,1,0,0,1,0,1,0,0,0,1]*10 def count0(lst):     c = 0     x in lst:         c += not x     return c '''  setup3 = ''' = [1,1,0,0,1,0,1,0,0,0,1]*10 def count0(lst):     c = 0     x in lst:         c += 1 - x     return c '''  setup4 = ''' = [1,1,0,0,1,0,1,0,0,0,1]*10 def count0(lst):     c = 0     x in lst:         c += 1^x     return c '''  print(min(timeit.timer('count0(a)', setup=setup1).repeat(10, 100000))) print(min(timeit.timer('count0(a)', setup=setup2).repeat(10, 100000))) print(min(timeit.timer('count0(a)', setup=setup3).repeat(10, 100000))) print(min(timeit.timer('count0(a)', setup=setup4).repeat(10, 100000))) 

0.276657819748
0.35341501236
0.265990972519
0.320657014847

2.7.5


Comments

Popular posts from this blog

How to understand 2 main() functions after using uftrace to profile the C++ program? -

c# - Update a combobox from a presenter (MVP) -

How to put a lock and transaction on table using spring 4 or above using jdbcTemplate and annotations like @Transactional? -