Sub topic 3
Nondeterminism and NFAs
Prerequisites and the NFA model
This chapter assumes that you know alphabets, strings, languages, sets, and deterministic finite automata (DFAs). An NFA, or nondeterministic finite automaton, is a finite-state machine that may have several possible next states for the same current state and input symbol.
Formally, an NFA is a five-tuple:
- \(Q\): a finite set of states
- \(\Sigma\): an input alphabet
- \(\delta: Q \times \Sigma \to 2^Q\): a transition function
- \(q_0 \in Q\): the start state
- \(F \subseteq Q\): the accepting states
The notation \(2^Q\) means the set of all subsets of \(Q\). Therefore, a transition can return zero, one, or many states.
An NFA accepts a string if at least one possible computation path consumes the entire string and finishes in an accepting state. A path that gets stuck does not matter if another path accepts.
A worked NFA
Consider the language
\[ L = \{xabb \mid x \in \{a,b\}^*\}. \]
This is the set of binary strings that end with abb. The NFA can remain in state 0 while scanning any prefix. When it reads an a, it can also guess that this a begins the final suffix.
For the input aabb, one possible path is:
- State 0 reads the first
aand stays in state 0. - State 0 reads the second
aand moves to state 1. - State 1 reads
band moves to state 2. - State 2 reads
band moves to state 3.
Because this path reaches state 3, the NFA accepts aabb. The input abab has no path that ends in state 3 after all symbols are consumed, so it is rejected.
Simulating an NFA
A practical simulation tracks a set of current states rather than one state. At each input symbol, compute every state reachable from any state in the current set.
nfa = {(0, 'a'): {0, 1}, (0, 'b'): {0}, (1, 'b'): {2}, (2, 'b'): {3}}
accepting = {3}
def nfa_accepts(w):
current = {0}
for ch in w:
current = {
q
for state in current
for q in nfa.get((state, ch), set())
}
return bool(current & accepting)
print(nfa_accepts("aabb")) # True
print(nfa_accepts("abab")) # FalseThe expression current & accepting checks whether at least one possible state is accepting.
Common errors
- Requiring every path to accept. NFA acceptance requires only one accepting path.
- Forgetting that a path may disappear when no transition exists.
- Accepting as soon as an accepting state is reached. The entire input must be consumed.
- Treating an NFA transition as one state. Its result is a set of states.
Exercise
Does the NFA above accept the string abb? Explain briefly.
Show answer
Yes. It can move from state 0 to state 1 on the first a, then to state 2 and state 3 on the two b symbols.