mirror of
https://github.com/autistic-symposium/master-algorithms-py.git
synced 2025-04-29 20:26:07 -04:00
Create hash_set_linked_list.py
This commit is contained in:
parent
df0c4465f2
commit
918a38bc9e
58
arrays_and_strings/hash_set_linked_list.py
Normal file
58
arrays_and_strings/hash_set_linked_list.py
Normal file
@ -0,0 +1,58 @@
|
|||||||
|
class HashSet:
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
self.key_range = 131
|
||||||
|
self.bucket = [LL_Bucket() for _ in range(self.key_range)]
|
||||||
|
|
||||||
|
def _hash(self, key):
|
||||||
|
return key % self.key_range
|
||||||
|
|
||||||
|
def add(self, element: int) -> None:
|
||||||
|
bucket_index = self._hash(element)
|
||||||
|
self.bucket[bucket_index].insert(element)
|
||||||
|
|
||||||
|
def remove(self, element: int) -> None:
|
||||||
|
bucket_index = self._hash(element)
|
||||||
|
self.bucket[bucket_index].delete(element)
|
||||||
|
|
||||||
|
def contains(self, element: int) -> bool:
|
||||||
|
bucket_index = self._hash(element)
|
||||||
|
return self.bucket[bucket_index].exists(element)
|
||||||
|
|
||||||
|
|
||||||
|
class Node:
|
||||||
|
def __init__(self, value=None, next=None):
|
||||||
|
self.value = value
|
||||||
|
self.next = next
|
||||||
|
|
||||||
|
|
||||||
|
class LL_Bucket:
|
||||||
|
def __init__(self):
|
||||||
|
# add a pseud head
|
||||||
|
self.head = Node(0)
|
||||||
|
|
||||||
|
def insert(self, value):
|
||||||
|
if not self.exists(value):
|
||||||
|
self.head.next = Node(value, self.head.next)
|
||||||
|
else:
|
||||||
|
print(f'node {value} already exists')
|
||||||
|
|
||||||
|
def delete(self, value):
|
||||||
|
prev = self.head
|
||||||
|
current = self.head.next
|
||||||
|
while current is not None:
|
||||||
|
if current.value == value:
|
||||||
|
prev.next = current.next
|
||||||
|
return True
|
||||||
|
prev = current
|
||||||
|
current = current.next
|
||||||
|
return False
|
||||||
|
|
||||||
|
def exists(self, value):
|
||||||
|
current = self.head.next
|
||||||
|
while current is not None:
|
||||||
|
if current.value == value:
|
||||||
|
return True
|
||||||
|
current = current.next
|
||||||
|
return False
|
||||||
|
|
Loading…
x
Reference in New Issue
Block a user