【问题标题】:What is the computational complexity of `itertools.combinations` in python?python中`itertools.combinations`的计算复杂度是多少?
【发布时间】:2018-11-21 19:49:25
【问题描述】:
python 中的

itertools.combinations 是查找所有 r 项组合的强大工具,但是,我想了解它的计算复杂性

假设我想知道 nr 方面的复杂性,当然它会给我所有 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)

【问题讨论】:

  • 它将是 nCr,即 O(n 选择 r)
  • @juanpa.arrivillaga 对于元组生成,至少还有另一个因素 r。

标签: python time-complexity complexity-theory


【解决方案1】:

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

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

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

在这种分析中,我假设所有整数运算都是O(1),即使它们的大小没有界限。

【讨论】:

  • 伟大的工作;问题,对于n=4; r=2; -> O(12),是否仍应假定为O(1)
  • @KenanNo,因为方程依赖于 n 和 r。例如,当您对列表进行迭代时,运行时间为 O(n)。因为它依赖于n,其中 n 是列表的大小。现在,如果一个假设的列表大小为 12(即 n = 12),这并不意味着运行时间为 O(1)。因为只要您在大小为 100000 的列表上运行算法,运行时间就会增加。
【解决方案2】:

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

代码sn-p如下所示

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=Input Size

【讨论】:

  • 时间复杂度不是O(n!);它应该是 O(n! * n)。绘制图表无法告诉您时间复杂度;它只能给你线索。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-09-18
  • 1970-01-01
  • 2023-03-07
  • 2012-08-14
  • 1970-01-01
  • 2014-10-06
相关资源
最近更新 更多