Python中os.walk的时间复杂度
问题内容:
我必须计算算法的时间复杂度,但是在其中我叫os.walk,我不能认为它是单个操作,而是很多。
os.walk的来源让我感到困惑,因为文件树可能以多种方式排序(一个文件夹中有1.000.000个文件,或者每个文件夹中有一个文件和1.000.000文件夹。
我不是时间复杂度方面的专家,我不能确定应该考虑只是一次操作还是多次操作,因此这让我陷入了困境。不要计算simlink标志,我认为将其设置为false可以忽略它们。
PD:我在Komodo IDE中找到了os.walk的源,但是我不知道如何找到它们作为javadocs。
问题答案:
好吧…让我们浏览一下源代码:)
文件:http :
//docs.python.org/2/library/os.html#os.walk
def walk(top, topdown=True, onerror=None, followlinks=False):
islink, join, isdir = path.islink, path.join, path.isdir
try:
# Note that listdir and error are globals in this module due
# to earlier import-*.
# Should be O(1) since it's probably just reading your filesystem journal
names = listdir(top)
except error, err:
if onerror is not None:
onerror(err)
return
dirs, nondirs = [], []
# O(n) where n = number of files in the directory
for name in names:
if isdir(join(top, name)):
dirs.append(name)
else:
nondirs.append(name)
if topdown:
yield top, dirs, nondirs
# Again O(n), where n = number of directories in the directory
for name in dirs:
new_path = join(top, name)
if followlinks or not islink(new_path):
# Generator so besides the recursive `walk()` call, no additional cost here.
for x in walk(new_path, topdown, onerror, followlinks):
yield x
if not topdown:
yield top, dirs, nondirs
因为它是一个生成器,所以这全都取决于您走树的距离,但是看起来给定路径中文件/目录的总数O(n)
在哪里n
。