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.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  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. explore_steps = 0
  7. def h(x, m):
  8. return int(x*a - int(x*a) * m)
  9. def f(x, i, m):
  10. return (h(x, m) + i + 14*i*i) % m
  11. def f1(x, i, m):
  12. if i % 2 == 0:
  13. return (h(x, m) + i*i) % m
  14. return ((h(x, m) - i*i) % m + m) % m
  15. class HashTable:
  16. def __init__(self, m, hash_function, exploratory_function=None):
  17. self.m = m
  18. self.h = hash_function
  19. self.f = exploratory_function
  20. self.n = 0
  21. self.table = AlgoDatArray(m)
  22. def insert(self, x):
  23. global explore_steps
  24. i = 0
  25. while i < self.m:
  26. j = self.f(x.value, i, self.m)
  27. if self.is_free(j):
  28. self.table[j].value = x.value
  29. self.n += 1
  30. return True
  31. i += 1
  32. explore_steps += 1
  33. return False
  34. def search(self, x):
  35. global explore_steps
  36. i = 0
  37. while i < self.m:
  38. j = f(x, i, self.m)
  39. if self.table[j] == x:
  40. return True
  41. if self.table[j] == None:
  42. return False
  43. i += 1
  44. explore_steps += 1
  45. return False
  46. def delete(self, x):
  47. global explore_steps
  48. i = 0
  49. while i < self.m:
  50. j = f(x, i, self.m)
  51. if self.table[j].value == x:
  52. self.table[j].value = "DELETED"
  53. self.n -= 1
  54. return True
  55. if self.table[j].value is None:
  56. return False
  57. i += 1
  58. explore_steps += 1
  59. return False
  60. def __str__(self):
  61. return str(self.table)
  62. def alpha(self):
  63. return self.n / self.m
  64. def is_free(self, i):
  65. if self.table[i] == None:
  66. return True
  67. if self.table[i] == "DELETED":
  68. return True
  69. return False
  70. if __name__ == "__main__":
  71. z = read_int_sequence("../../seq1.txt")
  72. start = pfc()
  73. hash = HashTable(31, h, f)
  74. for algodat_value in z:
  75. hash.insert(algodat_value)
  76. print(hash)
  77. print(f"Alpha: {hash.alpha()}")
  78. hash.delete(11)
  79. hash.search(47)
  80. hash.search(243)
  81. print(hash)
  82. print(f"Alpha: {hash.alpha()}")
  83. print(f"Dauer: {pfc() - start:.4f}s")
  84. print(f"Sondierungsschritte: {explore_steps}")
  85. AlgoDatValue.summary()