This article mainly explains how to use the zipper method to implement dictionary examples. if you are interested, you can refer to the dictionary:
It is also called a scattered list. The biggest feature is to use the key to find its corresponding value. its time complexity is O (1 ).
In Python, how does one use a list to implement a dictionary?
The biggest problem with dictionary implementation by list is to solve the hash conflict. what should I do if the same location is obtained by calculating different keys in the list?
The simplest way is to use the zipper method.
Zipper: adds another list to each position in a list, so that a hash conflict can be stored. when the selected hash function is good enough,
The number of num is large enough to ensure that each list in the list contains only one element. The location of the element calculated based on the key.
Time to O (1.
Class MyDict: def _ init _ (self, num = 100): # specify the list size self. _ num = num self. _ lst = [] for _ in range (self. _ num): self. _ lst. append ([]) def update (self, key, value): # add key-value key_index = hash (key) % self. _ num for I, (k, v) in enumerate (self. _ lst [key_index]): if key = k: self. _ lst [key_index] [I] = [key, value] break else: self. _ lst [key_index]. append ([key, value]) def get (self, key): # pop-up value key_index = hash (key) % self based on the specified key. _ num for k, v in self. _ lst [key_index]: if k = key: return v else: raise KeyError ('No such {} key '. format (key) def pop (self, key): # Based on the key pop-up element and delete key_index = hash (key) % self. _ num for I, (k, v) in enumerate (self. _ lst [key_index]): if k = key: result = v self. _ lst. pop [self. _ num] (I) return result else: raise KeyError ('No such {} key '. format (key) def _ getitem _ (self, key): # you can use a subscript to set key_index = hash (key) % self. _ num for k, v in self. _ lst [key_index]: if k = key: return v else: raise KeyError ('No such {} key '. format (key) def keys (self): # obtain all keys for index in range (self. _ num): for k, v in self. _ lst [index]: yield k def values (self): # obtain all values for index in range (self. _ num): for k, v in self. _ lst [index]: yield v def items (self): # retrieve all entries for index in range (self. _ num): for item in self. _ lst [index]: yield item
Time found by key, visible
The above is the details of the example of implementing the dictionary using the zipper method. For more information, see other related articles in the first PHP community!