Created
January 15, 2015 05:39
-
-
Save atomictom/c856c946cccef9c1090f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class DFA(object): | |
def __init__(self, states=None, initial=None, finals=None, transitions=None): | |
""" states: set(state) | |
initial: state (string) | |
finals: set(state) | |
transitions: {state: {symbol: state}} | |
""" | |
self.states = {} | |
self.finals = set() | |
if initial: | |
self.initial = initial | |
def set_initial(self, name): | |
self.initial = name | |
def add_state(self, name, transitions, is_final=False): | |
self.states[name] = transitions | |
if is_final: | |
self.finals.add(name) | |
def run(self, input): | |
cur_state = self.initial | |
for c in input: | |
cur_state = self.states[cur_state][c] | |
return cur_state in self.finals | |
def main(): | |
dfa = DFA(initial="q0") | |
dfa.add_state("q0", {"0": "q0", "1": "q1"}, is_final=True) | |
dfa.add_state("q1", {"0": "q2", "1": "qc"}, is_final=False) | |
dfa.add_state("q2", {"0": "q1", "1": "q2"}, is_final=False) | |
dfa.add_state("qc", {"0": "q0", "1": "q1"}, is_final=False) | |
string = raw_input("Enter a string to test >>> ") | |
try: | |
result = dfa.run(string.strip()) | |
except: | |
print "Bad input" | |
else: | |
print "Accepted!" if result else "Rejected =(" | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment