Skip to content

Commit 3a0b8f7

Browse files
committed
add algorithms hash in python
1 parent ce22434 commit 3a0b8f7

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

python/hash.py

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
class HashTable:
2+
def __init__(self, size):
3+
self.size = size
4+
self.table = {}
5+
for i in range(size):
6+
self.table[i] = []
7+
8+
def hash(self, key):
9+
return key % self.size
10+
11+
def get(self, key):
12+
return self.table[self.hash(key)]
13+
14+
def put(self, key, value):
15+
bucket = self.table[self.hash(key)]
16+
if value not in bucket:
17+
bucket.append(value)
18+
19+
20+
table = HashTable(8) # inisialisasi instance table dengan size 8
21+
books = [
22+
"The Little Prince",
23+
"The Old Man and the Sea",
24+
"The Little Mermaid",
25+
"Beauty and the Beast",
26+
"The Last Leaf",
27+
]
28+
for book in books: # iterasi semua buku
29+
key = sum(map(ord, book))
30+
table.put(key, book)
31+
32+
for key in table.table.keys():
33+
print(key, table.table[key])

0 commit comments

Comments
 (0)