Sub topic 14
The CYK Algorithm for Membership
Prerequisites and purpose
This chapter assumes that you know context-free grammars, derivations, and basic dynamic programming. It also assumes that you can convert a grammar to Chomsky normal form (CNF). In CNF, every production has one of these forms:
- \(A \rightarrow BC\), where \(B\) and \(C\) are variables.
- \(A \rightarrow a\), where \(a\) is a terminal.
- Optionally, \(S \rightarrow \epsilon\) for the start variable.
The CYK algorithm decides whether a string belongs to the language generated by a CFG in CNF. CYK is also called the Cocke–Younger–Kasami algorithm.
The table idea
For an input string \(w = w1w2\ldots w_n\), CYK builds a triangular table. Each cell stores the variables that can derive one substring.
For example, for aabb:
| Span | Substring | Meaning |
|---|---|---|
| `(1, 2)` | `aa` | variables deriving the first two symbols |
| `(2, 3)` | `ab` | variables deriving the middle two symbols |
| `(1, 4)` | `aabb` | variables deriving the whole string |
The algorithm first fills cells for substrings of length one. If \(A \rightarrow a\), it records \(A\) in every cell containing a.
It then considers longer substrings. To fill the cell for substring \(wi\ldots wj\), try every split point \(k\). If a rule \(A \rightarrow BC\) exists, and \(B\) derives the left part while \(C\) derives the right part, add \(A\) to the cell.
The string is accepted exactly when the start variable appears in the cell for the complete string.
def cyk(word, rules, start="S"):
"""Return whether word is generated by a CNF grammar.
Rules use tuples such as ("S", ("A", "B")) or ("A", ("a",)).
"""
n = len(word)
if n == 0:
return False # Handle S -> epsilon separately when needed.
table = [[set() for _ in range(n)] for _ in range(n)]
for i, symbol in enumerate(word):
for left, right in rules:
if right == (symbol,):
table[i][i].add(left)
for length in range(2, n + 1):
for i in range(n - length + 1):
j = i + length - 1
for k in range(i, j):
for left, right in rules:
if len(right) == 2:
b, c = right
if b in table[i][k] and c in table[k + 1][j]:
table[i][j].add(left)
return start in table[0][n - 1]
rules = [
("S", ("A", "B")),
("S", ("A", "X")),
("X", ("S", "B")),
("A", ("a",)),
("B", ("b",)),
]
print(cyk("aabb", rules)) # True
print(cyk("aab", rules)) # FalseComplexity and exam use
There are \(O(n^2)\) substrings, \(O(n)\) split points for each substring, and a fixed number of grammar rules to test. Therefore, the running time is \(O(n^3|G|)\), where \(|G|\) is the grammar size. The table uses \(O(n^2|G|)\) space.
Exercise
Why must a grammar be converted to CNF before applying the basic CYK algorithm?
Show answer
CYK assumes that every nonterminal expansion either produces one terminal or combines exactly two variables, so each table entry can be computed from two smaller spans.