Sub topic 2
Pushdown automata: states, stack, and transitions
This chapter assumes you know finite automata, regular expressions, and the basic idea of a context-free grammar (CFG). It also assumes you have seen the pumping lemma for regular languages.
A pushdown automaton (PDA) is a finite automaton with an extra stack. The stack is a last-in, first-out memory that the machine can push to and pop from. Because of the stack, a PDA can match counts, such as the number of a's against the number of b's, which a finite automaton cannot do.
A PDA move reads an input symbol (or nothing, an epsilon move), checks the top of the stack, changes state, and pushes or pops symbols.
Acceptance modes
A PDA can accept in two ways. It accepts by final state if it ends in an accepting state after reading the whole input. It accepts by empty stack if it has read the whole input and the stack is empty. Both modes recognise the same class of languages, so you can convert between them.
From CFG to PDA and back
Every CFG has an equivalent PDA, and every PDA has an equivalent CFG. The usual construction for a CFG to a PDA pushes the start symbol and then repeatedly expands a variable on top of the stack or matches a terminal against the input. The reverse direction builds variables that stand for "pops this stack symbol while consuming this substring."
def accepts_anbn(w):
stack = []
i = 0
while i < len(w) and w[i] == "a":
stack.append("A")
i += 1
while i < len(w) and w[i] == "b" and stack:
stack.pop()
i += 1
return i == len(w) and not stack and len(w) > 0
print(accepts_anbn("aabb")) # True
print(accepts_anbn("aab")) # False
print(accepts_anbn("")) # FalseDeterministic and nondeterministic PDAs
A deterministic PDA (DPDA) has at most one move for each combination of state, input symbol, and stack top. A nondeterministic PDA (NPDA) may have several moves. NPDAs recognise all context-free languages. DPDAs recognise a strictly smaller class, the deterministic context-free languages. For example, the language of even-length palindromes needs nondeterminism, because the machine must guess where the middle is.
> Note: in GATE questions, check whether the question asks about DCFLs or CFLs. The answer often changes.
The pumping lemma for context-free languages
If a language L is context-free, there is a number p such that every string z in L with length at least p can be split into z = uvwxy, where |vwx| ≤ p, |vx| ≥ 1, and u v^i w x^i y is in L for every i ≥ 0. To show a language is not context-free, pick a string, let an opponent split it, and find a pumped string outside the language.
Exercise:
Exercise
Why can a PDA accept {a^n b^n | n ≥ 1} but a finite automaton cannot?
Show answer
The PDA pushes one symbol for each a and pops one for each b, so the stack holds the count. A finite automaton has a fixed number of states and cannot keep an unbounded count.