首頁  >  文章  >  後端開發  >  如何有效比較不可哈希物件的無序列表?

如何有效比較不可哈希物件的無序列表?

Mary-Kate Olsen
Mary-Kate Olsen原創
2024-11-15 02:38:02959瀏覽

How to Efficiently Compare Unordered Lists of Non-Hashable Objects?

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中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn