python中的“ itertools.combinations”的计算复杂度是多少?

时间:2018-11-21 19:49:26

标签: python time-complexity complexity-theory

python中的

itertools.combinations是用于查找 r 术语的所有组合的强大工具,但是,我想了解其计算复杂度

比方说,我想了解 n r 的复杂性,并且肯定会给我所有 r 术语组合从 n 项列表中。

根据官方文档,这是粗略的实现。

def combinations(iterable, r):
    # combinations('ABCD', 2) --> AB AC AD BC BD CD
    # combinations(range(4), 3) --> 012 013 023 123
    pool = tuple(iterable)
    n = len(pool)
    if r > n:
        return
    indices = list(range(r))
    yield tuple(pool[i] for i in indices)
    while True:
        for i in reversed(range(r)):
            if indices[i] != i + n - r:
                break
        else:
            return
        indices[i] += 1
        for j in range(i+1, r):
            indices[j] = indices[j-1] + 1
        yield tuple(pool[i] for i in indices)

2 个答案:

答案 0 :(得分:1)

我想说的是θ[r (n choose r)]n choose r部分是生成器必须yield的次数,也是外部while迭代的次数。

在每次迭代中,至少需要生成长度为r的输出元组,它给出了附加因数r。其他外部循环也将在每个外部迭代中O(r)

这假设元组的生成实际上是O(r),并且在给定算法中的特定访问模式的情况下,至少平均而言,列表的确是O(1)。如果不是这种情况,那么仍然Ω[r (n choose r)]

像往常一样,在这种分析中,我假设所有整数运算均为O(1),即使它们的大小不受限制。

答案 1 :(得分:1)

我也有同样的问题(针对itertools.permutations),并且很难找到复杂性。 这导致我使用matplotlib.pyplot可视化代码;

代码段如下所示

result=[]
import matplotlib.pyplot as plt
import math
x=list(range(1,11))
def permutations(iterable, r=None): 
    count=0
    global result
    pool = tuple(iterable)
    n = len(pool)
    r = n if r is None else r
    if r > n:
        return
    indices = list(range(n))
    cycles = list(range(n, n-r, -1))
    yield tuple(pool[i] for i in indices[:r])
    while n:
        for i in reversed(range(r)):
            count+=1
            cycles[i] -= 1
            if cycles[i] == 0:
                indices[i:] = indices[i+1:] + indices[i:i+1]
                cycles[i] = n - i
            else:
                j = cycles[i]
                indices[i], indices[-j] = indices[-j], indices[i]
                yield tuple(pool[i] for i in indices[:r])
                break
        else:
            resulte.append(count)
            return
for j in x:
    for i in permutations(range(j)):
        continue

x=list(range(1,11))
plt.plot(x,result)

Time Complexity graph for itertools.permutation

从图中可以看出,时间复杂度为O(n!),其中n =输入大小