This repository was archived by the owner on Nov 4, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathhash_set_linked_list.py
62 lines (47 loc) · 1.6 KB
/
hash_set_linked_list.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# author: bt3gl
class HashSet:
def __init__(self, size):
self.size = size
self.bucket = [Bucket() for _ in range(self.size)]
def _get_hash_key(self, key):
return key % self.size
def add(self, element: int) -> None:
bucket_index = self._get_hash_key(element)
self.bucket[bucket_index].insert(element)
def remove(self, element: int) -> None:
bucket_index = self._get_hash_key(element)
self.bucket[bucket_index].delete(element)
def contains(self, element: int) -> bool:
bucket_index = self._get_hash_key(element)
return self.bucket[bucket_index].exists(element)
class Node:
def __init__(self, value=None, next=None):
self.value = value
self.next = next
class Bucket:
def __init__(self):
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