Python:在没有使用任何内置函数的情况下,从0和1的列表中计算0的数量的最优化方法是什么?

时间:2017-04-07 17:03:06

标签: python memory-management

好吧,我最近去接受采访,那家伙问我这个问题。

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? (Python) 

我猜他也是在内存管理方面的意思。

我对答案的确不太清楚,因为这些只是我想到的两件事。

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

但是,它没有使用任何内置函数,因此我想到的下一件事是for循环。

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

这也可以给出答案,而不使用任何内置函数,但我不认为这是最优化的方式,因为它一次又一次地循环遍历列表。

有人可以通过一些解释帮我解决这个问题吗?感谢

2 个答案:

答案 0 :(得分:1)

我认为最好的解决方案需要O(N)时间和O(1)空间。我会对您的代码进行一些调整。

counter = 0
for el in a:
    counter += not el
print(counter)

阻止你检查元素是否为零N次,并利用python中的布尔值为0或1

或者如果你可以使用len

counter = len(a)
for el in a:
    counter -= el
print(counter)

答案 1 :(得分:1)

为了它的价值,我做了几个时间。

import timeit

setup1 = '''
a = [1,1,0,0,1,0,1,0,0,0,1]*10
def count0(lst):
    c = 0
    for x in lst:
        if x == 0:
            c += 1
    return c
'''

setup2 = '''
a = [1,1,0,0,1,0,1,0,0,0,1]*10
def count0(lst):
    c = 0
    for x in lst:
        c += not x
    return c
'''

setup3 = '''
a = [1,1,0,0,1,0,1,0,0,0,1]*10
def count0(lst):
    c = 0
    for x in lst:
        c += 1 - x
    return c
'''

setup4 = '''
a = [1,1,0,0,1,0,1,0,0,0,1]*10
def count0(lst):
    c = 0
    for 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