Implement the CYK parsing algorithm for grammars in Chomsky normal form. Fill the DP table where each cell contains non-terminals that can generate the corresponding substring.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
I'm providing a Python implementation of the CYK algorithm that fills a DP table with non-terminals generating each substring based on a grammar in Chomsky normal form, along with an example grammar and usage.
Here's a straightforward implementation of the Cocke–Younger–Kasami algorithm in Python. It assumes your grammar is already in Chomsky normal form, i.e. productions are either of the form (A \to a) (a single terminal) or (A \to B C) (two non‑terminals). The dynamic programming table table[i][ℓ] is a set of all non‑terminals that can derive the substring w[i:i+ℓ+1].
python
from collections import defaultdict
def cyk_parse(w, start_symbol, unary_rules, binary_rules):
"""
CYK parser for CNF grammars.
:param w: input string to parse
:param start_symbol: the grammar's start symbol, e.g. "S"
:param unary_rules: dict mapping a terminal to a list of A with productions A -> terminal
e.g. {'a': ['A', 'C'], 'b': ['B']}
:param binary_rules: dict mapping (B,C) tuple to a list of A with productions A -> B C
e.g. {('A','B'): ['S'], ('B','C'): ['S'], ('C','C'): ['B'], ...}
:return: the filled CYK table (list of lists of sets)
"""
n = len(w)
# table[i][ℓ] corresponds to substring w[i:i+ℓ+1]
table = [[set() for _ in range(n)] for _ in range(n)]
# Initialize length-1 substrings (ℓ = 0)
for i, ch in enumerate(w):
for A in unary_rules.get(ch, ()):
table[i][0].add(A)
# Fill the table for substrings of length 2..n
for length in range(2, n + 1): # current substring length
ℓ_index = length - 1 # column index in table
for i in range(0, n - length + 1): # start of the substring
for split in range(1, length): # split point of the substring
left_set = table[i][split - 1]
right_set = table[i + split][length - split - 1]
for B in left_set:
for C in right_set:
for A in binary_rules.get((B, C), ()):
table[i][ℓ_index].add(A)
return table, (start_symbol in table[0][n - 1])
# Example usage:
if __name__ == '__main__':
# Grammar in CNF:
# S -> AB | BC
# A -> BA | a
# B -> CC | b
# C -> AB | a
unary = {'a': ['A', 'C'], 'b': ['B']}
binary = {
('A', 'B'): ['S', 'C'],
('B', 'C'): ['S'],
('B', 'A'): ['A'],
('C', 'C'): ['B'],
}
w = "baaba"
table, derives = cyk_parse(w, 'S', unary, binary)
print("Derivable from S:", derives)
# Pretty-print the table
for ℓ in range(len(w)-1, -1, -1):
row = []
for i in range(0, len(w) - ℓ):
row.append("{" + ",".join(sorted(table[i][ℓ])) + "}")
print(row)
The binary_rules and unary_rules dictionaries are “reversed” for efficiency: they map the right‑hand side back to the possible left‑hand side non‑terminals. After calling cyk_parse, table[0][len(w)-1] contains exactly the set of non‑terminals that can derive the entire string; the boolean derives tells you whether the start symbol is among them.