Skip to content

Instantly share code, notes, and snippets.

@tamago324
Created July 26, 2020 12:44
Show Gist options
  • Save tamago324/c447c3496b9966b2d0e03cb51db43007 to your computer and use it in GitHub Desktop.
Save tamago324/c447c3496b9966b2d0e03cb51db43007 to your computer and use it in GitHub Desktop.
0 を偶数個含む文字列の言語を受理する DFA
"""
0 を偶数個含む文字列の言語を受理する DFA
"""
from enum import Enum, auto
class DFA:
def __init__(self, states, alphabets, transition_method, start_state, accept_state):
# self.states = states
# self.alphabets = alphabets
self.transition_method = transition_method
# self.start_state = start_state
self.accept_state = accept_state
self.cur_state = start_state
def run(self, input_str: str) -> bool:
""" 入力文字列を読み出し、受理するかどうかを返す
"""
for s in input_str:
self.cur_state = self.transition(s)
return self.cur_state in self.accept_state
def transition(self, alphabet):
""" 遷移 """
return self.transition_method.get((self.cur_state, alphabet))
class States(Enum):
q1 = auto()
q2 = auto()
# 遷移関数 f(q, a)
# 状態が q のときに、a を読みだしたときの遷移先を表す
transition_method = {
(States.q1, "0"): States.q2,
(States.q1, "1"): States.q1,
(States.q2, "0"): States.q1,
(States.q2, "1"): States.q2,
}
dfa = DFA(
states={States.q1, States.q2},
alphabets={"0", "1"},
transition_method=transition_method,
start_state=States.q1,
accept_state={States.q1},
)
print(dfa.run("0101")) # True
print(dfa.run("01010")) # False
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment