Efficiently Comparing Unordered Lists of Non-Hashable Objects
Unordered lists (not sets) pose a challenge when comparing them for equality, as their elements can be in any order. This difficulty becomes more pronounced when dealing with non-hashable objects, such as instances of user-defined classes.
To facilitate such comparisons, various approaches exist with varying time complexities:
O(n)
For hashable objects, Counter provides an optimal solution:
def compare(s, t): return Counter(s) == Counter(t)
O(n log n)
If the objects are orderable, sorted offers a suitable alternative:
def compare(s, t): return sorted(s) == sorted(t)
O(n * n)
When neither hashability nor orderability is available, a straightforward approach using equality can be employed:
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
By choosing the appropriate solution based on the nature of your objects, you can efficiently compare unordered lists, even when the elements are not hashable or orderable.
위 내용은 해시할 수 없는 객체의 순서가 지정되지 않은 목록을 효율적으로 비교하는 방법은 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!