Skip to content

Instantly share code, notes, and snippets.

@fsndzomga
Created March 26, 2024 18:20
Show Gist options
  • Save fsndzomga/e664044921ddbd971eb3f2d88643751f to your computer and use it in GitHub Desktop.
Save fsndzomga/e664044921ddbd971eb3f2d88643751f to your computer and use it in GitHub Desktop.
class DFA:
def __init__(self):
self.states = ['q0', 'q1']
self.alphabet = ['0', '1']
self.transition_function = {
('q0', '0'): 'q1',
('q0', '1'): 'q0',
('q1', '0'): 'q0',
('q1', '1'): 'q1',
}
self.start_state = 'q0'
self.accept_states = ['q0']
def accepts(self, input_string):
current_state = self.start_state
for symbol in input_string:
if symbol not in self.alphabet:
return False # Reject if an invalid symbol is found
current_state = self.transition_function[(current_state, symbol)]
return current_state in self.accept_states
# Example usage
dfa = DFA()
print(dfa.accepts("0101")) # Should return True, even number of 0s
print(dfa.accepts("010101")) # Should return False, odd number of 0s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment