Repository navigation
Expand file tree
/
Copy pathChaining.py
More file actions
78 lines (66 loc) · 2.01 KB
/
Copy pathChaining.py
File metadata and controls
78 lines (66 loc) · 2.01 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
76
77
78
class Node:
def __init__(self, data):
self.data = data
self.next = None
class Linkedlist:
def __init__(self):
self.head = None
def insert(self, data):
current = self.head
if current is None:
self.head = Node(data)
else:
while current.next:
current = current.next
current.next = Node(data)
def traverse(self):
current = self.head
result = ''
while current:
result += (f"{current.data}->")
current = current.next
result+= "None"
print(result)
class HashData:
def __init__(self):
self.table = [None] * 10
def get_hash(self, key):
return key % 10
def setitem(self, key):
#insert key into the hash table
h = self.get_hash(key)
#check if the hash table is empty
if self.table[h] is None:
#create a new linked list and insert the key
self.table[h] = Linkedlist()
#insert the key into the linked list
self.table[h].insert(key)
else:
self.table[h].insert(key)
def display(self):
for hash_value, key in enumerate(self.table):
if key is not None:
print(f"{hash_value}:", end=" ")
key.traverse()
else:
print(f"{hash_value}: None")
def getitem(self, key):
h = self.get_hash(key)
if self.table[h] is not None:
current = self.table[h].head
while current:
if current.data == key:
return {"hash_value": h, "key": key}
current = current.next
return "Key not found"
else:
return "Key not found"
keys = [12, 17, 15, 4, 27, 14, 37]
hash = HashData()
for key in keys:
hash.setitem(key)
hash.display()
print(hash.getitem(15))
print(hash.getitem(14))
print(hash.getitem(37))
print(hash.getitem(100))