class DFA:
def __init__(self, states, alphabet, transition, start, accept):
self.states = states
self.alphabet = alphabet
self.transition = transition
self.start = start
self.accept = accept
def accepts(self, input_str):
current = self.start
for symbol in input_str:
if (current, symbol) in self.transition:
current = self.transition[(current, symbol)]
else:
return False
return current in self.accept
# Define a DFA that accepts strings ending with 'ab'
states = {'q0', 'q1', 'q2'}
alphabet = {'a', 'b'}
transition = {('q0', 'a'): 'q1', ('q0', 'b'): 'q0',
('q1', 'a'): 'q1', ('q1', 'b'): 'q2',
('q2', 'a'): 'q1', ('q2', 'b'): 'q0'}
start = 'q0'
accept = {'q2'}
dfa = DFA(states, alphabet, transition, start, accept)
print(dfa.accepts('aab')) # True
print(dfa.accepts('aba')) # False
print(dfa.accepts('babab')) # True