3
3
4
4
5
5
class Automaton :
6
- def __init__ (self , keywords : List [str ]):
7
- self .adlist = list ()
6
+ def __init__ (self , keywords : list [str ]):
7
+ self .adlist : list [ dict ] = list ()
8
8
self .adlist .append (
9
9
{"value" : "" , "next_states" : [], "fail_state" : 0 , "output" : []}
10
10
)
@@ -22,9 +22,8 @@ def find_next_state(self, current_state: int, char: str) -> Union[int, None]:
22
22
def add_keyword (self , keyword : str ) -> None :
23
23
current_state = 0
24
24
for character in keyword :
25
- if self .find_next_state (current_state , character ):
26
- current_state = self .find_next_state (current_state , character )
27
- else :
25
+ next_state = self .find_next_state (current_state , character )
26
+ if next_state is None :
28
27
self .adlist .append (
29
28
{
30
29
"value" : character ,
@@ -35,10 +34,12 @@ def add_keyword(self, keyword: str) -> None:
35
34
)
36
35
self .adlist [current_state ]["next_states" ].append (len (self .adlist ) - 1 )
37
36
current_state = len (self .adlist ) - 1
37
+ else :
38
+ current_state = next_state
38
39
self .adlist [current_state ]["output" ].append (keyword )
39
40
40
41
def set_fail_transitions (self ) -> None :
41
- q = deque ()
42
+ q : deque = deque ()
42
43
for node in self .adlist [0 ]["next_states" ]:
43
44
q .append (node )
44
45
self .adlist [node ]["fail_state" ] = 0
@@ -68,18 +69,21 @@ def search_in(self, string: str) -> Dict[str, List[int]]:
68
69
>>> A.search_in("whatever, err ... , wherever")
69
70
{'what': [0], 'hat': [1], 'ver': [5, 25], 'er': [6, 10, 22, 26]}
70
71
"""
71
- result = dict () # returns a dict with keywords and list of its occurrences
72
+ result : dict = (
73
+ dict ()
74
+ ) # returns a dict with keywords and list of its occurrences
72
75
current_state = 0
73
76
for i in range (len (string )):
74
77
while (
75
78
self .find_next_state (current_state , string [i ]) is None
76
79
and current_state != 0
77
80
):
78
81
current_state = self .adlist [current_state ]["fail_state" ]
79
- current_state = self .find_next_state (current_state , string [i ])
80
- if current_state is None :
82
+ next_state = self .find_next_state (current_state , string [i ])
83
+ if next_state is None :
81
84
current_state = 0
82
85
else :
86
+ current_state = next_state
83
87
for key in self .adlist [current_state ]["output" ]:
84
88
if not (key in result ):
85
89
result [key ] = []
0 commit comments