File tree Expand file tree Collapse file tree
DSA-Python/DataStructures Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ """
2+ LookUp by key -----> O(1)
3+ Insertion/Deletion -----> O(1)
4+
5+ Classes to implement HashTable in different languages:
6+ Python :: dictionary
7+ Java :: HashMap
8+ Java :: Linked HashMap
9+ C++ :: std::map
10+ """
11+
12+ class HashTable ():
13+ """
14+ In class hashTable, an array of size '100' is created which is initialised using list_comprehension; val in each
15+ element is None
16+ """
17+ def __init__ (self ):
18+ self .MAX = 100 # size of array = 100
19+ self .arr = [None for i in range (self .MAX )] # list-comprehension
20+
21+
22+ def get_hash (self , key ):
23+ h = 0
24+ for char in key :
25+ h += ord (char ) # returns ASCII val of char
26+ return h % self .MAX # hash: Sum(ASCII_Values(key)) % size(array)
27+
28+ def add (self , key , val ):
29+ h = self .get_hash (key ) # retrieving hash function
30+ self .arr [h ] = val
31+
32+ def get (self , key ):
33+ h = self .get_hash (key )
34+ return self .arr [h ]
35+
36+ def delete (self , key ):
37+ h = self .get_hash (key )
38+ self .arr [h ] = None
39+
40+
41+
42+
43+ t = HashTable () # object of class HashTable
44+ q = t .add ('Google' , 120 )
45+ r = t .get ('Google' )
46+ # s = t.arr # to get full array
47+ # m = t.delete('Google') # delete element by key
48+ # n = t.arr # to get full array after deleting
49+ print (r )
50+
51+ # todo Collision Handling
52+ # Collision Handling: When one or more elements are assigned the same hash
53+
54+ s = t .add ('Google' , 121 )
55+ z = t .get ('Google' )
56+ print (z )
57+
You can’t perform that action at this time.
0 commit comments