How is set() implemented?

后端 未结 6 1690
旧时难觅i
旧时难觅i 2020-11-22 15:07

I\'ve seen people say that set objects in python have O(1) membership-checking. How are they implemented internally to allow this? What sort of data structure d

6条回答
  •  悲哀的现实
    2020-11-22 15:30

    I think its a common mistake, set lookup (or hashtable for that matter) are not O(1).
    from the Wikipedia

    In the simplest model, the hash function is completely unspecified and the table does not resize. For the best possible choice of hash function, a table of size n with open addressing has no collisions and holds up to n elements, with a single comparison for successful lookup, and a table of size n with chaining and k keys has the minimum max(0, k-n) collisions and O(1 + k/n) comparisons for lookup. For the worst choice of hash function, every insertion causes a collision, and hash tables degenerate to linear search, with Ω(k) amortized comparisons per insertion and up to k comparisons for a successful lookup.

    Related: Is a Java hashmap really O(1)?

提交回复
热议问题