Skip to content

Instantly share code, notes, and snippets.

@hwayne
Created July 14, 2016 16:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hwayne/1b21693ed95569536e6180fcf05c4fa6 to your computer and use it in GitHub Desktop.
Save hwayne/1b21693ed95569536e6180fcf05c4fa6 to your computer and use it in GitHub Desktop.
Type checking a DFA
from abc import ABCMeta
from enum import Enum
import typing as t
class AbstractDFA:
...
T = t.TypeVar('T', bound=t.Type[AbstractDFA])
class State(t.Generic[T]):
def __init__(self, dfa: T) -> None:
self.transitions = (None, None) # type: t.Tuple[State[T], State[T]]
def transition(self, token: int) -> 'State[T]':
if token:
return self.transitions[1]
else:
return self.transitions[0]
class DFA(t.Generic[T]):
def __init__(self, start_state: State[T], success_states: t.Sequence[State[T]]) -> None:
self.start_state = start_state
self.success_states = success_states
def test_string(self, input_string: t.Iterable[int]) -> bool:
current_state = self.start_state
for letter in input_string:
current_state = current_state.transition(letter)
return current_state in self.success_states
class Ones(AbstractDFA):
...
class Zeros(AbstractDFA):
...
a, b, c, d = State(Ones), State(Ones), State(Zeros), State(Zeros)
a.transitions = (a, b)
b.transitions = (b, b)
c.transitions = (c, d)
d.transitions = (d, d)
OnesDFA = DFA(a, [b])
def dfa_str(s: str) -> t.Iterable[int]:
return map(int, s)
print(OnesDFA.test_string(dfa_str("000000000")))
print(OnesDFA.test_string(dfa_str("000000010")))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment