设置与'&'的交集如何在引擎盖下工作?
set_1 = {1, 2, 3, 4, 5, 6, 7}
set_2 = {2, 4, 6, 8, 10, 12}
intersec = set_1 & set_2
当&在两组之间使用时,引擎盖下会发生什么?它的时间复杂度是多少?
回答
的set数据结构,和它的操作,在C实现的源代码可以在GitHub中找到,该文件中Objects/setobject.c。为了那些不会写 C 的人的利益,这里是它在 Python 中的工作原理的粗略翻译:
# helper function; only self needs to be a set
def set_intersection(self, other):
if self is other:
return self.copy()
result = set()
if isinstance(other, (set, frozenset)):
if len(other) > len(self):
self, other = other, self
for item in other:
if item in self:
result.add(item)
return result
# when using the & operator; self and other both must be sets
def set_and(self, other):
if not isinstance(self, (set, frozenset)) or not isinstance(other, (set, frozenset)):
return NotImplemented
return set_intersection(self, other)
# when using the .intersection method, which accepts multiple "other" arguments
def set_intersection_multi(self, *others):
if not others:
return self.copy()
result = self
for other in others:
result = set_intersection(result, other)
return result
这不是字面翻译;C 代码有一个循环用于 whereother是集合的情况,另一个循环是当它不是集合时,因为在前一种情况下,项目散列是已知的,不需要重新计算。没有办法翻译那个细节,所以 C 中的两个循环都可以翻译成 Python 中的同一个循环,我简化了它。另一个不可翻译的区别是,在 C 中,如果self是 afrozenset那么结果也是;但是.add在这种情况下不能使用 Python 代码。
因为测试成员(所述in一组操作者)花费O(1)的预期时间,则交叉点的预期时间复杂度是O(分钟(M,N))时两者都是集合,其中m和n是的长度self和other。
当other不是集合时,交集的预期时间复杂度等于迭代other的时间复杂度,加上计算 中所有项的哈希的时间复杂度other。这通常是 O(n),但理论上可能更高。