-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhashing.py
More file actions
89 lines (69 loc) · 2.38 KB
/
hashing.py
File metadata and controls
89 lines (69 loc) · 2.38 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
79
80
81
82
83
84
85
86
87
88
89
# ============================================
# TWO HASHING METHODS
# ============================================
def division_hash(key, table_size):
return key % table_size
def mid_square_hash(key, table_size):
square = key * key
mid = (square // 10) % table_size
return mid
# ============================================
# HASH TABLE USING CHAINING (Division Method)
# ============================================
class HashTable:
def __init__(self, size):
self.size = size
self.table = [[] for _ in range(size)]
# ---------- Insert ----------
def insert(self, key):
index = division_hash(key, self.size)
if key not in self.table[index]:
self.table[index].append(key)
print(f"{key} inserted at index {index}")
else:
print("Key already exists")
# ---------- Search ----------
def search(self, key):
index = division_hash(key, self.size)
if key in self.table[index]:
print(f"{key} found at index {index}")
else:
print(f"{key} not found")
# ---------- Delete ----------
def delete(self, key):
index = division_hash(key, self.size)
if key in self.table[index]:
self.table[index].remove(key)
print(f"{key} deleted from index {index}")
else:
print(f"{key} not found")
# ---------- Display ----------
def display(self):
print("\nHash Table:")
for i in range(self.size):
print(f"{i} : {self.table[i]}")
# ============================================
# MENU-DRIVEN DRIVER CODE
# ============================================
if __name__ == "__main__":
size = int(input("Enter hash table size: "))
ht = HashTable(size)
while True:
print("\n1.Insert 2.Search 3.Delete 4.Display 5.Exit")
choice = int(input("Enter choice: "))
if choice == 1:
key = int(input("Enter key to insert: "))
ht.insert(key)
elif choice == 2:
key = int(input("Enter key to search: "))
ht.search(key)
elif choice == 3:
key = int(input("Enter key to delete: "))
ht.delete(key)
elif choice == 4:
ht.display()
elif choice == 5:
print("Exiting program...")
break
else:
print("Invalid choice")