-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhashmap.py
More file actions
75 lines (54 loc) · 1.77 KB
/
hashmap.py
File metadata and controls
75 lines (54 loc) · 1.77 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
class HashMap:
def __init__(self,capacity):
self.capacity = capacity
self.size = 0
self.buckets = [[] for _ in range(capacity)]
def __len__(self):
return self.size
def __contains__(self,key):
index = self._hashfuction(key)
bucket = self.buckets[index]
for k,v in bucket:
if k == key:
return True
return False
def put(self,key,value):
index = self._hashfuction(key)
bucket = self.buckets[index]
for i , (k,v) in enumerate(bucket):
if k == key:
bucket[i] = (key,value)
break
else:
bucket[key].append((key,value))
self.size+=1
def get(self,key):
index = self._hashfuction(key)
bucket = self.buckets[index]
for k,v in bucket:
if k == key:
return v
raise ValueError("Key Not Found!")
def remove(self,key):
index = self._hashfuction(key)
bucket = self.buckets[index]
for i, (k,v) in enumerate(bucket):
if k == key:
del bucket[i]
self.size-=1
break
else:
raise ValueError("Key Not Found!")
def keys(self):
return [k for bucket in self.buckets for k,v in bucket]
def values(self):
return [v for bucket in self.buckets for k,v in bucket]
def items(self):
return [(k,v) for bucket in self.buckets for k,v in bucket]
# within the class
def _hashfuction(self,key):
key_string = str(key)
hash_result = 0
for char in key_string:
hash_result = (hash_result * 31 + ord(char)) % self.capacity
return hash_result