Python issubset()的复杂性
给定两组A和B及其长度:A=len(A)和B=len(B),其中A>=B。Python 2.7的issubset()函数的复杂性是什么,即B.issubset(A)?我可以从互联网上找到两个相互矛盾的答案: 1、O(a)或O(b) 可从以下地址找到: 和bit.ly/1AWB1QU (很抱歉,我无法发布更多http链接,因此我必须使用缩短url。) 我从Python官方网站下载了源代码,发现:Python issubset()的复杂性,python,performance,loops,time-complexity,Python,Performance,Loops,Time Complexity,给定两组A和B及其长度:A=len(A)和B=len(B),其中A>=B。Python 2.7的issubset()函数的复杂性是什么,即B.issubset(A)?我可以从互联网上找到两个相互矛盾的答案: 1、O(a)或O(b) 可从以下地址找到: 和bit.ly/1AWB1QU (很抱歉,我无法发布更多http链接,因此我必须使用缩短url。) 我从Python官方网站下载了源代码,发现: def issubset(self, other): """Report whether an
def issubset(self, other):
"""Report whether another set contains this set."""
self._binary_sanity_check(other)
if len(self) > len(other): # Fast check for obvious cases
return False
for elt in ifilterfalse(other._data.__contains__, self):
return False
return True
这里只有一个回路
2,O(a*b)
查找自:bit.ly/1Ac7geK
我还发现一些代码看起来像Python的源代码:bit.ly/1CO9HXa,如下所示:
def issubset(self, other):
for e in self.dict.keys():
if e not in other:
return False
return True
这里有两个循环
那么哪一个是正确的呢?有人能详细回答一下上述两种解释的区别吗?非常感谢。假设A中的
e是常数时间,那么B.issubset(A)
的复杂性是O(len(B))
这通常是一个合理的假设,但很容易被坏的哈希函数所违背。例如,如果A
的所有元素具有相同的散列码,则B.issubset(A)
的时间复杂度将恶化为O(len(B)*len(A))
在第二个代码段中,复杂性与上面相同。如果你仔细看,只有一个循环;另一个是if
语句(如果e不在其他语句中:
)