sidrs

DSAL_ AS Ass 1

Jan 5th, 2025
149
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.68 KB | None | 0 0
  1. ### Linear Probing method for handling collisions
  2.  
  3. def insert(hasht, n):
  4.     key = int(input("Enter the value to be inserted: "))
  5.     loc = key % n
  6.     if (hasht[loc] == -1):
  7.         hasht[loc] = key
  8.     else:
  9.         while (hasht[loc] != -1):
  10.             loc = (loc + 1) % n
  11.         hasht[loc] = key
  12.  
  13. def display(hasht):
  14.     print("\nHashtable: ", hasht)
  15.  
  16.  
  17. def search(hasht, size):
  18.     key = int(input("Enter the element to be searched: "))
  19.     start = key % size
  20.     i = start
  21.     flag = 0
  22.     found = -1
  23.     while (True):
  24.         if (hasht[i] == key):
  25.             flag = 1
  26.             found = i
  27.             break
  28.         else:
  29.             flag = 0
  30.         i = (i + 1) % size
  31.         if (i == start):
  32.             break
  33.  
  34.     if (flag == 0):
  35.         print("\nKey not found")
  36.     if (flag == 1):
  37.         print("\nKey found at position: ", found)
  38.  
  39. def main():
  40.     size = int(input("Enter the size of the Hash Table: "))
  41.  
  42.     hasht = []
  43.     for i in range(0, size):
  44.         hasht.append(-1)
  45.  
  46.     count = 0
  47.    
  48.     while (True):
  49.         print("\n----- MENU -----")
  50.         print("1. Insert")
  51.         print("2. Display")
  52.         print("3. Search")
  53.         print("4. Exit")
  54.         ch = input("Enter your choice: ")
  55.         if ch == "1":
  56.             if (count >= size):
  57.                 print("\nCannot Insert! The Hash Table is full")
  58.             else:
  59.                 insert(hasht, size)
  60.                 display(hasht)
  61.                 count += 1
  62.         elif ch == "2":
  63.             display(hasht)
  64.         elif ch == "3":
  65.             search(hasht, size)
  66.         elif ch == "4":
  67.             return
  68.         else:
  69.             print("Invalid Input")
  70.  
  71.  
  72. main()
Advertisement
Add Comment
Please, Sign In to add comment