-
Notifications
You must be signed in to change notification settings - Fork 0
/
vocab.py
33 lines (26 loc) · 953 Bytes
/
vocab.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
from collections import defaultdict
class Vocabulary:
def __init__(self, max_size):
self.max_size = max_size
self.current_size = 0
self.table = dict()
self.inverse_table = dict()
def add(self, word) -> int:
if word not in self.inverse_table and not self.is_full():
word_index = self.current_size
self.inverse_table[word] = word_index
self.table[word_index] = word
self.current_size += 1
return word_index
elif word in self.inverse_table:
word_index = self.inverse_table[word]
return word_index
else:
return -1
def is_full(self) -> bool:
return self.current_size == self.max_size
def __getitem__(self, word: str):
if word in self.inverse_table:
word_index = self.inverse_table[word]
return word_index
return -1