-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHashTable.py
73 lines (58 loc) · 2.09 KB
/
HashTable.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
"""Doc."""
class HashTable:
"""."""
def __init__(self, n=100):
"""Construtor."""
self.hash_table = [None] * n
self.chaves = []
def funcao_hash(self, chave):
"""."""
return hash(chave) % len(self.hash_table)
def adiciona(self, chave, conteudo):
"""Adiciona."""
if not self.hash_table[self.funcao_hash(chave)]:
self.chaves.append(chave)
self.hash_table[self.funcao_hash(chave)] = [[chave, conteudo]]
else:
if chave in self.chaves:
for i in self.hash_table[self.funcao_hash(chave)]:
if i[0] == chave:
i[1] = conteudo
break
else:
self.chaves.append(chave)
self.hash_table[self.funcao_hash(chave)].\
append([chave, conteudo])
return self
def busca(self, chave, padrao=None):
"""Busca."""
if chave not in self.chaves or (
not self.hash_table[self.funcao_hash(chave)]):
return padrao
for i in self.hash_table[self.funcao_hash(chave)]:
if i[0] == chave:
return i[1]
return padrao
def remove(self, chave):
"""Remove elemento por chave."""
if chave not in self.chaves or \
not self.hash_table[self.funcao_hash(chave)]:
return False
if len(self.hash_table[self.funcao_hash(chave)]) == 1:
self.hash_table[self.funcao_hash(chave)] = None
else:
for i, j in enumerate(self.hash_table[self.funcao_hash(chave)]):
if j[0] == chave:
self.hash_table[self.funcao_hash(chave)].pop(i)
break
for i, j in enumerate(self.chaves):
if chave == j:
self.chaves.pop(i)
return self
def __iter__(self):
"""Iterador."""
for i in [(chave, self.busca(chave)) for chave in self.chaves]:
yield i
def __len__(self):
"""Retorna tamanho."""
return len(self.chaves)