37 lines
884 B
Python
37 lines
884 B
Python
|
|
|
|
class FiniteStateMachine(object):
|
|
def __init__(self, start: int, valid: list, default: int, transitions: dict):
|
|
self._start = start
|
|
self._valid = valid
|
|
|
|
self._transitions = dict()
|
|
for state, trans in transitions.items():
|
|
self._transitions[state] = dict()
|
|
for words, target in trans.items():
|
|
for word in words:
|
|
self._transitions[state][word] = target
|
|
|
|
self._default = default
|
|
self._state = start
|
|
|
|
def reset(self):
|
|
self._state = self._start
|
|
|
|
def make_transition(self, word):
|
|
if(not self._state in self._transitions):
|
|
self._state = self._default
|
|
if(not word in self._transitions[self._state]):
|
|
self._state = self._default
|
|
return
|
|
|
|
self._state = self._transitions[self._state][word]
|
|
|
|
def check(self, sequence):
|
|
for word in sequence:
|
|
self.make_transition(word)
|
|
is_valid = self._state in self._valid
|
|
self.reset()
|
|
return is_valid
|
|
|