简体   繁体   English

Python3 list.count()时间复杂度

[英]Python3 list.count() time complexity

I've been having a lot of trouble finding documentation on this. 我一直在寻找有关此文档的麻烦。 What is the time complexity of list.count() in Python 3? Python 3中list.count()的时间复杂度是多少? I've been assuming it's just O(n), does anyone know if this is the case? 我一直以为只是O(n),有人知道这是不是这种情况?

You can try a bit of an experiment using the timeit module. 您可以使用timeit模块尝试一下实验。

Timing list.count(0) over a large range of list lengths ( 10**0 to 10**6 ). 在很大范围的列表长度( 10**010**6 )中对list.count(0)进行计时。

from timeit import timeit
from math import log10
import matplotlib.pyplot as plt

data = []
for i in [10**x for x in range(6)]:
    data.append((i, timeit.timeit('x.count(0)', setup='x=list(range(%d))' % i, number=1000)))

Taking the log of both time and list length for better visualisation (note we are using log10 here, to match the range of list lengths). 记录时间和列表长度的日志以更好地可视化(请注意,此处我们使用log10来匹配列表长度的范围)。

log_data = [log10(x), log10(y) for (x,y) in data]

Generate a quick plot. 生成快速绘图。

plt.figure()
plt.scatter(*zip(*log_times))
plt.xlabel('log(n)')
plt.ylabel('log(time)')
plt.savefig('count_complexity')

在此处输入图片说明

It seems that it is indeed O(n) complexity. 看来确实是O(n)复杂性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM