You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

hash_table.py 2.1KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. from SoSe24.algodat.foundation import AlgoDatArray, AlgoDatValue, read_int_sequence, MinusInf
  2. from time import perf_counter as pfc
  3. #Goldener Schnitt
  4. import math
  5. a = (math.sqrt(5) - 1) / 2
  6. def h(x, m):
  7. return int(x*a - int(x*a) * m)
  8. def f(x, i, m):
  9. return (h(x, m) + i + 14*i*i) % m
  10. def f1(x, i, m):
  11. if i % 2 == 0:
  12. return (h(x, m) + i*i) % m
  13. return ((h(x, m) - i*i) % m + m) % m
  14. class HashTable:
  15. def __init__(self, m, h, f=None):
  16. self.m = m
  17. self.h = h
  18. self.f = f
  19. self.table = AlgoDatArray(m)
  20. def insert(self, x):
  21. i = 0
  22. while i < self.m:
  23. j = self.f(x.value, i, self.m)
  24. if self.is_free(j):
  25. self.table[j].value = x.value
  26. return True
  27. i += 1
  28. return False
  29. def search(self, x):
  30. i = 0
  31. while i < self.m:
  32. j = f(x, i, self.m)
  33. if self.table[j] == x:
  34. return True
  35. if self.table[j] == None:
  36. return False
  37. i += 1
  38. return False
  39. def delete(self, x):
  40. i = 0
  41. while i < self.m:
  42. j = f(x, i, self.m)
  43. if self.table[j].value == x:
  44. self.table[j].value = "DELETED"
  45. return True
  46. if self.table[j].value is None:
  47. return False
  48. i += 1
  49. return False
  50. def __str__(self):
  51. return str(self.table)
  52. def alpha(self):
  53. i=0
  54. used = 0
  55. while i < self.m:
  56. used += 0 if self.is_free(i) else 1
  57. i += 1
  58. return used / self.m
  59. def is_free(self, i):
  60. if self.table[i] == None:
  61. return True
  62. if self.table[i] == "DELETED":
  63. return True
  64. return False
  65. if __name__ == "__main__":
  66. z = read_int_sequence("../../seq1.txt")
  67. start = pfc()
  68. hash = HashTable(31, h, f)
  69. for i in z:
  70. hash.insert(i)
  71. print(hash)
  72. print(f"Alpha: {hash.alpha()}")
  73. hash.delete(34)
  74. hash.search(47)
  75. hash.search(243)
  76. print(hash)
  77. print(f"Alpha: {hash.alpha()}")
  78. print(f"Dauer: {pfc() - start:.4f}s")
  79. AlgoDatValue.summary()