fork download
  1. # your code goes here
  2. class HashMap:
  3. def __init__(self,m):
  4. self.m=m
  5. self.map=[0]*m
  6. self.frq=[0]*m
  7. self.state=[0]*m
  8. def hash_function(self,k):
  9. return k%self.m
  10. def insert(self,k):
  11. id=self.hash_function(k)
  12. while self.state[id]!=0:
  13. if self.map[id]==k:
  14. self.frq[id]+=1
  15. self.state[id]=1
  16. return
  17. id=(id+1)%self.m
  18. self.map[id]=k
  19. self.state[id]=1
  20. self.frq[id]+=1
  21. def search(self,k):
  22. id=self.hash_function(k)
  23. while self.map[id]!=k:
  24. if self.state[id]==0 or self.state[id]==-1:
  25. return False
  26. id=(id+1)%self.m
  27. if self.map[id]==k and self.state[id]==1:
  28. return True
  29. return False
  30. def delete(self,k):
  31. if self.search(k):
  32. id=self.hash_function(k)
  33. while self.map[id]!=k:
  34. id=(id+1)%self.m
  35. self.frq[id]-=1
  36. self.state[id]=-1
  37. return True
  38. return False
  39. def display(self):
  40. print(f"{'Index':<7}{'Key':<7}{'State':<7}{'Freq':<7}")
  41. print("-"*28)
  42. for i in range(self.m):
  43. print(f"{i:<7}{self.map[i]:<7}{self.state[i]:<7}{self.frq[i]:<7}")
  44.  
  45. hm=HashMap(10)
  46. hm.insert(5)
  47. hm.insert(12)
  48. hm.insert(19)
  49. hm.insert(26)
  50. hm.insert(33)
  51.  
  52. print(hm.delete(19))
  53. print(hm.delete(40))
  54.  
  55. print(hm.search(26))
  56.  
  57. hm.display()
  58.  
Success #stdin #stdout 0.1s 13960KB
stdin
Standard input is empty
stdout
True
False
True
Index  Key    State  Freq   
----------------------------
0      0      0      0      
1      0      0      0      
2      12     1      1      
3      33     1      1      
4      0      0      0      
5      5      1      1      
6      26     1      1      
7      0      0      0      
8      0      0      0      
9      19     -1     0