python - How are finite automata implemented in code? -
how 1 implement dfa
or nfa
matter in python code?
what ways in python? , ever used in real world projects?
a straightforward way represent dfa dictionary of dictionaries. each state create dictionary keyed letters of alphabet , global dictionary keyed states. example, following dfa wikipedia article on dfas
can represented dictionary this:
dfa = {0:{'0':0, '1':1}, 1:{'0':2, '1':0}, 2:{'0':1, '1':2}}
to "run" dfa against input string drawn alphabet in question (after specifying initial state , set of accepting values) straightforward:
def accepts(transitions,initial,accepting,s): state = initial c in s: state = transitions[state][c] return state in accepting
you start in initial state, step through string character character, , @ each step next state. when done stepping through string check if final state in set of accepting states.
for example
>>> accepts(dfa,0,{0},'1011101') true >>> accepts(dfa,0,{0},'10111011') false
for nfas store sets of possible states rather individual states in transition dictionaries , use random
module pick next state set of possible states.
Comments
Post a Comment