Regular grammar to automaton
Build the automaton for a regular grammar (rules like A → aB): each nonterminal is a state and each rule an edge; then try a string on it.
In a regular (right-linear) grammar each rule is either A → aB (the symbol a, then the nonterminal B) or
A → a (a last symbol). That is exactly the shape of an automaton:
- Time:
O(rules + |w| · edges) - Space:
O(rules) - Johnsonbaugh, chapter 12
- Grimaldi, chapter 6
S → aS | bA, A → bA | b: strings of a's followed by at least two b's. aabb belongs to the language.
def grammar_to_automaton(rules, w):# rules like "S=aA|b;A=bS": capital letters are nonterminals, small letters terminals.# Each rule A → aB becomes an edge A --a--> B, and A → a an edge A --a--> F (the final state).states = []edges = []for rule in rules.split(";"):if "=" not in rule:return Nonelhs, rhs = rule.split("=")if lhs not in states:states.append(lhs)for option in rhs.split("|"):target = option[1] if len(option) > 1 else "F"edges.append([lhs, option[0], target])states.append("F")# Run the automaton on w, keeping every state it could be in.current = [states[0]]for i in range(len(w)):reached = set()for s, a, t in edges:if s in current and a == w[i]:reached.add(t)current = sorted(reached)accepted = "F" in currentreturn accepted
Start
The table is still empty.
Local variables
Orange = changed in this step
Call stack
- grammar_to_automaton()line 1
Explanation
The idea
In a regular (right-linear) grammar each rule is either A → aB (the symbol a, then the nonterminal B) or
A → a (a last symbol). That is exactly the shape of an automaton:
- each nonterminal is a state; the start symbol is the start state;
A → aBis an edgeA --a--> B;A → ais an edgeA --a--> F, whereFis a new final state.
A string is in the grammar's language exactly when the automaton reaches F from the start state by reading it. So
regular grammars and finite automata describe exactly the same languages.
The input
Rules are separated by ; and options by |: for example S=aS|bA;A=bA|b. Capital letters are nonterminals and
small letters terminals. The automaton may be nondeterministic, so a set of states is followed at once.