Skip to content

Instantly share code, notes, and snippets.

@atomictom
Created January 15, 2015 05:40
Show Gist options
  • Select an option

  • Save atomictom/b60dd7e39d0ae5948681 to your computer and use it in GitHub Desktop.

Select an option

Save atomictom/b60dd7e39d0ae5948681 to your computer and use it in GitHub Desktop.
class SymbolException(Exception):
pass
def make_dfa(symbols, states, start, finals, transitions):
def dfa(input):
cur_state = start
for cur_input in input:
if cur_input not in symbols:
raise SymbolException
cur_state = transitions[cur_state][cur_input]
return cur_state in finals
return dfa
def main():
symbols = "01"
states = set("q0 q1 q2 qc".split())
start = "q0"
finals = {"q0"}
transitions = {
"q0": {"0": "q0", "1": "q1"},
"q1": {"0": "q2", "1": "qc"},
"q2": {"0": "q1", "1": "q2"},
"qc": {"0": "q0", "1": "q1"},
}
dfa = make_dfa(symbols, states, start, finals, transitions)
string = raw_input("Enter a string to test >>> ")
try:
result = dfa(string.strip())
except SymbolException:
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