-
Notifications
You must be signed in to change notification settings - Fork 267
/
hash_table.py
85 lines (69 loc) · 2.16 KB
/
hash_table.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
"""
Implementação de uma hashtable
"""
import traceback
class HashTable:
def __init__(self, size=10):
self.size = size
self.tables = [[] for _ in range(self.size)]
def hashing(self, key):
return hash(key) % self.size
def __setitem__(self, key, value):
hash_key = self.hashing(key)
bucket = self.tables[hash_key]
if bucket:
for index, k_value in enumerate(bucket):
k, v = k_value
if key == k:
bucket[index] = key, value
return
bucket.append((key, value))
def __getitem__(self, key):
hash_key = self.hashing(key)
bucket = self.tables[hash_key]
if bucket:
for index, item in enumerate(bucket):
k, value = item
if key == k:
return value
raise KeyError(key)
def __delitem__(self, key):
hash_key = self.hashing(key)
bucket = self.tables[hash_key]
if bucket:
for index, item in enumerate(bucket):
k, value = item
if key == k:
del bucket[index]
return
raise KeyError(key)
if __name__ == "__main__":
# Cria as tabelas de dispersão
hash_table = HashTable()
# Insere as chaves e valores
for i in range(143):
hash_table[i] = hex(round(i * 23))
# Deletar item
print("Deletar chave 0 de valor: ", hash_table[0])
del hash_table[0]
# Procurar item
print("Valor da chave 23: ", hash_table[23])
# Subscrever um valor de uma chave
hash_table[1] = "TESTE DE SUBSCREVER"
# Exibir dispersão
for i, table in enumerate(hash_table.tables):
print(
"Table {index} -> {table} Len -> {len}".format(
index=i + 1, table=table, len=len(table)
)
)
# Tentar deletar uma chave que não existe
try:
del hash_table[493084]
except KeyError:
print(traceback.print_exc())
# Tentar acessar uma chave que não existe
try:
print(hash_table[493084])
except KeyError:
print(traceback.print_exc())