O(n) : Counter()方法最好(如果你的对象是可散列的):
def compare(s, t): return Counter(s) == Counter(t)
O(n log n) : sorted()方法次好(如果对象是可订购的):
def compare(s, t): return sorted(s) == sorted(t)
O(n * n) :如果对象既不可散列也不可订购,则可以使用等式:
def compare(s, t): t = list(t) # make a mutable copy try: for elem in s: t.remove(elem) except ValueError: return False return not t
你可以sorting两个:
sorted(a) == sorted(b)
计数sorting也可能更高效(但要求对象可哈希)。
>>> from collections import Counter >>> a = [1, 2, 3, 1, 2, 3] >>> b = [3, 2, 1, 3, 2, 1] >>> print (Counter(a) == Counter(b)) True
如果你知道这些项目总是可以被哈希的,你可以使用一个Counter() ,它是O(n)
如果你知道这些项目总是可sorting的,你可以使用sorted() ,它是O(n log n)
在一般情况下,你不能依靠能够sorting,或有元素,所以你需要像这样的后备