The "Dictionary dict" and "set set" of several common black boxes in Python

Source: Internet
Author: User

Here is the "dictionary dict" and "Set set" types, first of all, to understand, for Python, the standard hashing mechanism is provided by the hash function, for the call to a __hash__ method:

>>> Hash (56>>>) hash ("I like Python")-4698211515002810579

The mechanism for this standard hashing is often used for the implementation of the dictionary type (dict), and dict is what we typically call a hash table. Similarly, the collection type (set) is implemented through this mechanism.

The most important point: the composition of the hash value is basically done in constant time, and even if its behind-the-scenes array is long enough, the average time we use the hash value for its access is O (1).

This means that when we access the elements in the dict and set, the time we consume is constant.

Note:The hash method is especially useful for building hash tables. For other hashes such as passwords, there is a standard library called the Hashlib module

Let's look at an example of a good practice for the above:

>>> from random import randrange>>> L = [Randrange (10000)-I in range (+)]>>> in Lfalse >>> S = set (L) >>> Lfalse

As we can see from the above example, the second method constructs a set on top of the list. It seems pointless, but it really depends on the actual situation, because:

The second method should be worthwhile when we are going to query the "L" in the previous example, because the query of the member (without knowing the subscript) is linear in the time complexity of the list, but it is really constant in set.

When we want to add a new value to a collection in turn, and check whether the new value is added successfully in each step, the run time will be squared if the list is used, but you can get the linear level time with set set.

The "Dictionary dict" and "set set" of several common black boxes in Python

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.