Skip to content

Instantly share code, notes, and snippets.

@mkscrg
Created December 2, 2010 19:18
Show Gist options
  • Save mkscrg/725879 to your computer and use it in GitHub Desktop.
Save mkscrg/725879 to your computer and use it in GitHub Desktop.
A test Gist! (Some Python functions playing with deterministic finite automata.)
"""
Arguments are the parameters of a deterministic finite automaton:
q -- states (list of strings)
si -- input alphabet (list of characters)
de -- transition function ((index of q),(index of si) --> (index of q))
s -- start state (index of q)
f -- accept states (list of (index of q))
Returns a generator function which takes a string and generates successive
states (indices of q) as the DFA runs on the string.
"""
def make_dfa(q, si, de, s, f):
def dfa(instr):
state = s
yield state
while instr:
state = de(state, si.index(instr[0]))
yield state
instr = instr[1:]
return
dfa.q = q
dfa.si = si
dfa.de = de
dfa.s = s
dfa.f = f
return dfa
"""
Takes:
dfa -- a generator function, such as is returned by make_dfa
instr -- a string as input to dfa
Produces a generator by calling dfa(instr), iterates the generator until
StopIteration, then returns True if the generator's final output is in dfa.f,
returns False otherwise.
"""
def run_dfa(dfa, instr):
for last in dfa(instr): pass
if last in dfa.f:
return True
else:
return False
"""
The next line has 80 characters, exactly:
01234567890123456789012345678901234567890123456789012345678901234567890123456789
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment