a = [1, 2, 3, 1, 2, 3]
b = [3, 2, 1, 3, 2, 1]
a 和 b 应该被认为是相等的,因为它们具有完全相同的元素,只是顺序不同。
问题是,我的实际列表将由对象(我的类实例)组成,而不是整数。
O(n): The 柜台() https://docs.python.org/3.5/library/collections.html#collections.Counter方法是最好的(如果你的对象是可散列的):
def compare(s, t):
return Counter(s) == Counter(t)
O(n log n): The sorted() https://docs.python.org/3.5/library/functions.html#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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)