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.
The CYK (Cocke-Younger-Kasami) algorithm is a parsing algorithm for context-free grammars in Chomsky Normal Form (CNF). Let me implement a comprehensive solution.
Key points about CYK:
Grammar must be in Chomsky Normal Form (CNF)
CNF rules are of two types:
A → BC (two non-terminals)
A → a (single terminal)
Uses dynamic programming with a table where table[i][j] contains all non-terminals that can derive substring from position i with length j+1
The algorithm:
Initialize the first row with terminals
For each span length from 2 to n:
For each starting position:
For each split point:
For each rule A → BC:
If B is in table[i][k] and C is in table[i+k+1][j-k-1], then add A to table[i][j]
Let me implement this with a clear structure:
python
class CNFGrammar:
def __init__(self):
self.terminal_rules = {} # A -> a: {a: [A, ...]}
self.non_terminal_rules = {} # A -> BC: {(B, C): [A, ...]}
def add_terminal_rule(self, non_terminal, terminal):
"""Add rule: non_terminal -> terminal"""
if terminal not in self.terminal_rules:
self.terminal_rules[terminal] = []
self.terminal_rules[terminal].append(non_terminal)
def add_non_terminal_rule(self, non_terminal, left, right):
"""Add rule: non_terminal -> left right"""
if (left, right) not in self.non_terminal_rules:
self.non_terminal_rules[(left, right)] = []
self.non_terminal_rules[(left, right)].append(non_terminal)
class CYKParser:
def __init__(self, grammar):
self.grammar = grammar
def parse(self, tokens):
"""
Parse a sequence of tokens using CYK algorithm
Args:
tokens: list of tokens/terminals
Returns:
DP table where table[i][j] contains non-terminals that
can generate substring from index i with span length j+1
"""
n = len(tokens)
if n == 0:
return None
# Initialize DP table with dimensions n x n, where each cell stores a set of non-terminals
table = [[set() for _ in range(n)] for _ in range(n)]
# Fill the base case: single tokens mapped to their non-terminals
for i in range(n):
token = tokens[i]
if token in self.grammar.terminal_rules:
for non_terminal in self.grammar.terminal_rules[token]:
table[i][0].add(non_terminal)
# Build up the table for progressively longer spans by trying all possible split points
for span_length in range(1, n):
for i in range(n - span_length):
for k in range(span_length):
left_set = table[i][k]
right_set = table[i+k+1][span_length-k-1]
for left_nt in left_set:
for right_nt in right_set:
if (left_nt, right_nt) in self.grammar.non_terminal_rules:
for parent in self.grammar.non_terminal_rules[(left_nt, right_nt)]:
table[i][span_length].add(parent)
return table
def is_accepted(self, tokens, start_symbol='S'):
"""Check if the tokens are accepted by the grammar"""
table = self.parse(tokens)
if table is None:
return False
n = len(tokens)
return start_symbol in table[0][n - 1]
def print_table(self, tokens, table):
"""Pretty print the parsing table"""
n = len(tokens)
print("\nCYK Parsing Table:")
print("=" * 80)
print("\nTokens:", tokens)
print("\nDP Table (table[i][j] = non-terminals generating tokens[i:i+j+1]):\n")
header = "Index |"
for j in range(n):
header += f"
span_j={j} (length={j+1}) |"
print(header)
print("-" * 80)
for i in range(n):
row = f" {i} |"
for j in range(n):
if i + j < n:
cell = ", ".join(sorted(table[i][j])) if table[i][j] else "∅"
row += f" {cell:20} |"
else:
row += f" {'—':20} |"
print(row)
print("-" * 80)
print(f"\nTable[0][{n-1}] (entire input): {table[0][n-1]}")
print("=" * 80)
def
The method validates whether tokens are accepted by checking if the start symbol appears in the final table entry. The print function formats the parsing table with headers showing span indices and lengths, displaying non-terminals for each cell or empty markers where applicable, and highlighting the result for the complete input span.
Now I need to define example grammars to test the parser. First, I'll create a simple natural language grammar with lexical rules mapping terminals like 'the', 'book', and 'flies' to parts of speech (N, V, D), then add syntactic rules to build noun phrases, verb phrases, and prepositional phrases up to complete sentences. After that, I'll set up an arithmetic expression grammar with numeric and operator terminals, followed by rules combining them into expressions. grammar.add_non_terminal_rule('E_OP', 'PLUS', 'E') # E_OP -> + E
grammar.add_non_terminal_rule('E', 'E', 'E_OP') # E -> E E_OP
return grammar
if __name__ == "__main__":
# Example 1: Natural Language
print("=" * 80)
print("EXAMPLE 1: Natural Language Parsing")
print("=" * 80)
grammar1 = create_example_grammar()
parser1 = CYKParser(grammar1)
# Test sentences
sentences = [
['the', 'book', 'flies'], # Should parse
['the', 'flights', 'book'], # May not parse
]
for sentence in sentences:
print(f"\
nParsing: {' '.join(sentence)}")
table = parser1.parse(sentence)
if table:
parser1.print_table(sentence, table)
is_accepted = parser1.is_accepted(sentence, 'S')
print(f"Accepted by grammar: {is_accepted}")
# Example 2: Simpler grammar
print("\n\n" + "=" * 80)
print("EXAMPLE 2: Simple Expression Grammar")
print("=" * 80)
grammar2 = CNFGrammar()
# a, b terminals
grammar2.add_terminal_rule('A', 'a')
grammar2.add_terminal_rule('B', 'b')
# S -> AA | BB
grammar2.add_non_terminal_rule('S', 'A', 'A')
grammar2.add_non_terminal_rule('S', 'B', 'B')
# A -> AA | a | AS
grammar2.add_non_terminal_rule('A',
'A', 'A')
grammar2.add_non_terminal_rule('A', 'A', 'S')
# B -> b | BB | SB
grammar2.add_non_terminal_rule('B', 'B', 'B')
grammar2.add_non_terminal_rule('B', 'S', 'B')
parser2 = CYKParser(grammar2)
test_strings = [
['a', 'a'],
['b', 'b'],
['a', 'a', 'a', 'a'],
['a', 'b'],
]
for test_str in test_strings:
print(f"\nParsing: {' '.join(test_str)}")
table = parser2.parse(test_str)
if table:
parser2.print_table(test_str, table)
is_accepted = parser2.is_accepted(test_str, 'S')
print(f"Accepted by grammar (S starts it): {is_accepted}")
I'm setting up a second test case with a simpler grammar that has terminals a and b, then defining production rules for S, A, and B. After instantiating the parser, I'm running it against four test strings to verify which ones the grammar accepts.
I should build out a more complete implementation with proper documentation. The CNFGrammar class needs to store terminal rules mapping each terminal to the non-terminals that produce it, and non-terminal rules mapping pairs of symbols to the non-terminals that expand to them. I'll add methods to insert both types of rules and a string representation to display the grammar structure.
For the CYKParser, I'm implementing the classic dynamic programming algorithm that fills a table where each cell [i,j] contains all non-terminals that can derive the substring from position i with length j. The algorithm starts by identifying which non-terminals produce each individual token, then iteratively builds up larger spans by checking all possible ways to split them into two parts and finding non-terminals with matching production rules. 1]
self.table = [[set() for _ in range(n)] for _ in range(n)]
# Step 1: Base case - fill diagonal (length 1 substrings)
self._fill_base_case()
# Step 2: Fill table for increasing span lengths
self._fill_table(n)
return self.table
def _fill_base_case(self) -> None:
"""Fill table[i][0] with terminals that generate tokens[i]"""
for i, token in enumerate(self.tokens):
if token in self.grammar.terminal_rules:
for non_terminal in self.grammar.terminal_rules[token]:
self.table[i][0].add(non_terminal)
def _fill_table(self, n: int) -> None
:
"""Fill the rest of the table using dynamic programming"""
for span_length in range(1, n):
for i in range(n - span_length):
for k in range(span_length):
left_cells = self.table[i][k]
right_cells = self.table[i + k + 1][span_length - k - 1]
For each span length, I iterate through starting positions and try all possible split points. At each split, I check which non-terminals can combine the left and right substrings according to the grammar rules. tokens: List[str]) -> Set[str]:
"""
Get all non-terminals that can generate the entire input.
Args:
tokens: List of input tokens
Returns:
Set of non-terminals that can parse the entire string
"""
table = self.parse(tokens)
if table is None or len(tokens) == 0:
return set()
n = len(tokens)
return table[0][n - 1]
def print_table(self, show_indices: bool = True) -> None:
"""
Pretty print the parsing table.
Args:
show_indices: Whether to show table indices
"""
if self.table is None or self.tokens is None:
print("No table available. Run parse() first.")
return
n = len(self.tokens)
print("\n" + "=" * 100)
print("CYK PARSING TABLE")
print("=" * 100)
print(f"\nInput tokens: {' '.join(self.tokens)}")
print(f"\nTable legend: table[i][j] = non-terminals generating tokens[i] to tokens[i+j]")
print("-" * 100)
# Print header with token indices
header = " i → |"
for j in range(n):
header += f" j={j:2d} |"
print(header)
print(" |" + "-" * (14 * n + 1))
# Print each row
for i in range(n):
print(f" i={i} |", end="")
for j in range(n):
if i + j < n:
cell_content = ", ".join(sorted(self.table[i][j]))
if not cell_content:
cell_content = "∅"
print(f" {cell_content:12} |", end="")
else:
print(f" {'—':12} |", end="")
print()
print("=" * 100)
print(f"\nFinal result table[0][{n-1}]: {sorted(self.table[0][n-1])}")
print("=" * 100 + "\n")
def example_natural_language():
"""Example: Simple natural language grammar"""
print("\n" + "=" * 100)
print("EXAMPLE 1: Natural Language Parsing")
print("=" * 100)
grammar = CNFGrammar()
# Terminal rules (lexical rules)
grammar.add_terminal_rule('N', 'dog')
grammar.add_terminal_rule('N', 'cat')
grammar.add_terminal_rule('N', 'telescope')
grammar.add_terminal_rule('D', 'the')
grammar.add_terminal_rule('D', 'a')
grammar.add_terminal_rule('V', 'sees')
grammar.add_terminal_rule('V', 'walks')
grammar.add_terminal_rule('P', 'with')
# Non-terminal rules (syntactic rules)
grammar.add_non_terminal_rule('NP', 'D', 'N')
grammar.add_non_terminal_rule('NP', 'NP', 'PP')
grammar.add_non_terminal_rule('VP', 'V', 'NP')
grammar.add_non_terminal_rule('VP', 'V', 'PP')
grammar.add_non_terminal_rule('VP', 'VP', 'PP')
grammar.add_non_terminal_rule('PP', 'P', 'NP')
grammar.add_non_terminal_rule('S', 'NP', 'VP')
print("\nGrammar:")
print(grammar)
parser = CYKParser(grammar)
test_cases = [
['the', 'dog', 'sees', 'a', 'cat'],
['a', 'cat', 'walks'],
['the', 'dog'],
['sees', 'cat'], # Invalid: no NP subject
]
for tokens in test_cases:
print(f"\nParsing: '{' '.join(tokens)}'")
parser.parse(tokens)
parser.print_table()
accepted = parser.is_accepted(tokens, 'S')
symbols = parser.get_accepted_symbols(tokens)
print(f"Accepted (S): {accepted}")
print(f"Can derive to: {symbols}\n")
def example_arithmetic():
"""Example: Simple arithmetic expression grammar"""
print("\n" + "=" * 100)
print("EXAMPLE 2: Arithmetic Expression Grammar")
print("=" * 100)
grammar = CNFGrammar()
# Terminals
grammar.add_terminal_rule('n', '2')
grammar.add_terminal_rule('n', '3')
grammar.add_terminal_rule('n', '5')
grammar.add_terminal_rule('Plus', '+')
grammar.add_terminal_rule('Mult', '*')
# Non-terminals: Converting standard rules to CNF
# E -> E + E | E * E | n
# Becomes:
# E -> E PlusOp |
For each test sentence, I parse the tokens and display the CYK table to show how the parser builds up constituents. I check whether the input can be accepted as a complete sentence and what symbols it can derive to. Then I move on to demonstrating arithmetic expressions, setting up terminals for numbers and operators, and converting the standard expression grammar into Chomsky Normal Form. .add_non_terminal_rule('SR', 'S', 'RP')
grammar.add_non_terminal_rule('S', 'S', 'S')
print("\nGrammar:")
print("S -> ( S ) | S S")
print("(In CNF)")
print(grammar)
parser = CYKParser(grammar)
test_cases = [
['(', ')'],
['(', '(', ')', ')'],
['(', ')', '(', ')'],
['(', ')'],
['(', '(', ')'], # Invalid
]
for tokens in test_cases:
print(f"\nParsing: '{' '.join(tokens)}'")
parser.parse(tokens)
parser.print_table()
accepted = parser.is_accepted(tokens, 'S')
print(f"Balanced: {accepted}\n")
if __name__ == "__main__":
example_natural_language()
example_arithmetic()
example_parentheses()
I'm checking whether each token sequence is accepted by the grammar and reporting the result. Then I'm running all three example functions to demonstrate the parser across different domains.</think>
# CYK Parsing Algorithm Implementation
Here's a complete implementation of the CYK algorithm with detailed documentation and examples:
```python
from typing import Set, Dict, Tuple, List, Optional
from dataclasses import dataclass
@dataclass
class ParseResult:
"""Result of CYK parsing"""
table: List[List[Set[str]]]
tokens: List[str]
accepted: bool
start_symbol: str
accepted_symbols: Set[str]
class CNFGrammar:
"""
Represents a context-free grammar in Chomsky Normal Form.
CNF Rules:
1. A -> BC (two non-terminals)
2. A -> a (single terminal)
"""
def __init__(self):
# terminal_rules[terminal] = [non-terminals that produce this terminal]
self.terminal_rules: Dict[str, List[str]] = {}
# non_terminal_rules[(B, C)] = [A where A -> BC]
self.non_terminal_rules: Dict[Tuple[str, str], List[str]] = {}
def add_terminal_rule(self, lhs: str, terminal: str) -> None:
"""Add rule: lhs -> terminal"""
if terminal not in self.terminal_rules:
self.terminal_rules[terminal] = []
if lhs not in self.terminal_rules[terminal]:
self.terminal_rules[terminal].append(lhs)
def add_non_terminal_rule(self, lhs: str, rhs1: str, rhs2: str) -> None:
"""Add rule: lhs -> rhs1 rhs2"""
key = (rhs1, rhs2)
if key not in self.non_terminal_rules:
self.non_terminal_rules[key] = []
if lhs not in self.non_terminal_rules[key]:
self.non_terminal_rules[key].append(lhs)
def __str__(self) -> str:
result = "Terminal Rules:\n"
for terminal, nts in sorted(self.terminal_rules.items()):
for nt in sorted(nts):
result += f" {nt} → {terminal}\n"
result += "\nNon-terminal Rules:\n"
for (rhs1, rhs2), nts in sorted(self.non_terminal_rules.items()):
for nt in sorted(nts):
result += f" {nt} → {rhs1} {rhs2}\n"
return result
class CYKParser:
"""
CYK (Cocke-Younger-Kasami) Parser for CNF grammars.
Algorithm Complexity: O(n³ · |G|) where n = input length, |G| = grammar size
DP Table Structure:
- table[i][j] = set of non-terminals that can generate tokens[i..i+j]
- i: starting position (0 to n-1)
- j: span length - 1 (0 to n-1)
"""
def __init__(self, grammar: CNFGrammar):
self.grammar = grammar
self.table: Optional[List[List[Set[str]]]] = None
self.tokens: Optional[List[str]] = None
def parse(self, tokens: List[str]) -> Optional[ParseResult]:
"""
Parse tokens using CYK algorithm.
Args:
tokens: Input token sequence
Returns:
ParseResult object containing DP table and parse information
"""
n = len(tokens)
if n == 0:
return None
self.tokens = tokens
# Initialize DP table: table[i][j] contains non-terminals
# that can generate tokens[i] through tokens[i+j]
self.table = [[set() for _ in range(n)] for _ in range(n)]
# Step 1: Fill base case (j=0, single tokens)
self._fill_base_case(n)
# Step 2: Fill table for increasing span lengths
self._fill_dp_table(n)
start_symbol = 'S'
accepted = start_symbol in self.table[0][n - 1]
accepted_symbols = self.table[0][n - 1]
return ParseResult(
table=self.table,
tokens=tokens,
accepted=accepted,
start_symbol=start_symbol,
accepted_symbols=accepted_symbols
)
def _fill_base_case(self, n: int) -> None:
"""Fill table[i][0] with non-terminals that generate tokens[i]"""
for i in range(n):
token = self.tokens[i]
if token in self.grammar.terminal_rules:
for nt in self.grammar.terminal_rules[token]:
self.table[i][0].add(nt)
def _fill_dp_table(self, n: int) -> None:
"""
Fill DP table for increasing span lengths.
For each span length j from 1 to n-1:
For each starting position i from 0 to n-j-1:
For each split point k from 0 to j-1:
If B ∈ table[i][k] and C ∈ table[i+k+1][j-k-1]:
For each rule A → BC:
Add A to table[i][j]
"""
for j in range(1, n): # span_length or j
for i in range(n - j): # start position
# Try all split points
for k in range(j): # k: relative split position
left_nts = self.table[i][k]
right_nts = self.table[i + k + 1][j - k - 1]
# Check all non-terminal rules
for left in left_nts:
for right in right_nts:
key = (left, right)
if key in self.grammar.non_terminal_rules:
for nt in self.grammar.non_terminal_rules[key]:
self.table[i][j].add(nt)
def is_accepted(self, tokens: List[str], start='S') -> bool:
"""Check if tokens are accepted by grammar"""
result = self.parse(tokens)
if result is None:
return False
return start in result.accepted_symbols
def visualize_table(self, result: ParseResult) -> None:
"""Visualize the parsing table in a clear format"""
n = len(result.tokens)
print("\n" + "=" * 120)
print("CYK PARSING TABLE VISUALIZATION")
print("=" * 120)
print(f"Input: {' '.join(result.tokens)}\n")
# Create header
print("Span length (j):")
header = " i↓ |"
for j in range(n):
header += f" j={j} (len={j+1}) |"
print(header)
print("Position|" + "-" * (26 * n + 2))
# Print each row
for i in range(n):
print(f" i={i} |", end="")
for j in range(n):
if i + j < n:
cell = ", ".join(sorted(result.table[i][j]))
if not cell:
cell = "∅"
# Pad to 22 characters
cell_str = cell[:20] if len(cell) > 20 else cell
print(f" {cell_str:22} |", end="")
else:
print(f" {'—':22} |", end="")
print()
print("=" * 120)
# Show interpretation
print("\nInterpretation:")
print(f" table[0][{n-1}] (entire input) = {sorted(result.accepted_symbols)}")
if 'S' in result.accepted_symbols:
print(f" ✓ Accepted: String can be parsed starting from 'S'")
else:
print(f" ✗ Rejected: String cannot be parsed from 'S'")
print("=" * 120 + "\n")
def print_parse_trace(self, result: ParseResult) -> None:
"""Print detailed parse trace"""
n = len(result.tokens)
print("\n" + "=" * 100)
print("DETAILED PARSE TRACE")
print("=" * 100 + "\n")
print("Input Tokens:")
for i, token in enumerate(result.tokens):
print(f" [{i}]: '{token}'")
print("\n" + "-" * 100)
print("Parse Table Population:")
print("-" * 100)
# Show base case
print("\nBase Case (j=0, single tokens):")
for i in range(n):
token = result.tokens[i]
nts = result.table[i][0]
if nts:
print(f" table[{i}][0] ('{token}'): {sorted(nts)}")
# Show span length progression
print("\nProgressive Parsing:")
for j in range(1, n):
print(f"\n Span length j={j} (substring length={j+1}):")
found_any = False
for i in range(n - j):
if result.table[i][j]:
tokens_covered = result.tokens[i:i+j+1]
print(f" table[{i}][{j}] ({' '.join(tokens_covered)}): {sorted(result.table[i][j])}")
found_any = True
if not found_any:
print(f" (No non-terminals found for this span length)")
print("\n" + "-" * 100)
print(f"Final Result: {sorted(result.accepted_symbols)}")
print("=" * 100 + "\n")
# ============================================================================
# EXAMPLES
# ============================================================================
def example_1_simple_sentences():
"""Example 1: Simple natural language parsing"""
print("\n" + "=" * 100)
print("EXAMPLE 1: Natural Language Parsing")
print("=" * 100)
grammar = CNFGrammar()
# Terminal rules (lexicon)
for word, pos in [
('dog', 'N'), ('cat', 'N'), ('flies', 'N'),
('sees', 'V'), ('eats', 'V'),
('the', 'D'), ('a', 'D'),
('with', 'P'), ('in', 'P'),
]:
grammar.add_terminal_rule(pos, word)
# Non-terminal rules (syntax)
grammar.add_non_terminal_rule('NP', 'D', 'N')
grammar.add_non_terminal_rule('NP', 'NP', 'PP')
grammar.add_non_terminal_rule('VP', 'V', 'NP')
grammar.add_non_terminal_rule('VP', 'VP', 'PP')
grammar.add_non_terminal_rule('PP', 'P', 'NP')
grammar.add_non_terminal_rule('S', 'NP', 'VP')
print("\nGrammar Rules:")
print(grammar)
parser = CYKParser(grammar)
test_cases = [
['the', 'cat', 'sees', 'a', 'dog'],
['a', 'dog', 'eats', 'the', 'cat'],
['the', 'sees'], # Invalid
]
for tokens in test_cases:
print(f"\n{'='*100}")
print(f"Parsing: {' '.join(tokens)}")
result = parser.parse(tokens)
if result:
parser.visualize_table(result)
parser.print_parse_trace(result)
def example_2_arithmetic():
"""Example 2: Arithmetic expressions"""
print("\n" + "=" * 100)
print("EXAMPLE 2: Arithmetic Expression Grammar")
print("=" * 100)
grammar = CNFGrammar()
# Terminals
for digit in ['1', '2', '3']:
grammar.add_terminal_rule('NUM', digit)
grammar.add_terminal_rule('PLUS', '+')
grammar.add_terminal_rule('TIMES', '*')
# CNF rules for: E → E + E | E * E | NUM
# Convert to: E → E OP | NUM
# OP_PLUS → + E
# OP_TIMES → * E
grammar.add_non_terminal_rule('E', 'NUM', 'NUM')
grammar.add_non_terminal_rule('E', 'E', 'OP_PLUS')
grammar.add_non_terminal_rule('E', 'E', 'OP_TIMES')
grammar.add_non_terminal_rule('OP_PLUS', 'PLUS', 'E')
grammar.add_non_terminal_rule('OP_TIMES', 'TIMES', 'E')
print("\nGrammar Rules:")
print(grammar)
parser = CYKParser(grammar)
test_cases = [
['2', '+', '3'],
['2', '+', '3', '*', '1'],
['1'],
['2', '+'], # Invalid
]
for tokens in test_cases:
print(f"\n{'='*100}")
print(f"Parsing: {' '.join(tokens)}")
result = parser.parse(tokens)
if result:
parser.visualize_table(result)
def example_3_balanced_parentheses():
"""Example 3: Balanced parentheses"""
print("\n" + "=" * 100)
print("EXAMPLE 3: Balanced Parentheses")
print("=" * 100)
grammar = CNFGrammar()
grammar.add_terminal_rule('LPAREN', '(')
grammar.add_terminal_rule('RPAREN', ')')
# S → (S) | SS becomes:
# S → LP SR
# SR → S RP
# S → S S
grammar.add_non_terminal_rule('S', 'LP', 'SR')
grammar.add_non_terminal_rule('SR', 'S', 'RP')
grammar.add_non_terminal_rule('S', 'S', 'S')
grammar.add_terminal_rule('LP', '(')
grammar.add_terminal_rule('RP', ')')
print("\nGrammar Rules (CNF for balanced parentheses):")
print(grammar)
parser = CYKParser(grammar)
test_cases = [
['(', ')'],
['(', '(', ')', ')'],
['(', ')', '(', ')'],
['(', '(', ')'], # Invalid
['(', ')'],
]
for tokens in test_cases:
print(f"\n{'='*100}")
print(f"Parsing: {''.join(tokens)}")
result = parser.parse(tokens)
if result:
parser.visualize_table(result)
status = "✓ BALANCED" if result.accepted else "✗ UNBALANCED"
print(f"Status: {status}\n")
def example_4_complex_analysis():
"""Example 4: Detailed analysis"""
print("\n" + "=" * 100)
print("EXAMPLE 4: Detailed Analysis - Step by Step")
print("=" * 100)
grammar = CNFGrammar()
# Simple grammar: S → NP VP; NP → D N; VP → V NP; N → dog; V → sees; D → the
grammar.add_terminal_rule('D', 'the')
grammar.add_terminal_rule('N', 'dog')
grammar.add_terminal_rule('V', 'sees')
grammar.add_non_terminal_rule('NP', 'D', 'N')
grammar.add_non_terminal_rule('VP', 'V', 'NP')
grammar.add_non_terminal_rule('S', 'NP', 'VP')
print("\nGrammar:")
print(grammar)
parser = CYKParser(grammar)
tokens = ['the', 'dog', 'sees', 'the', 'dog']
print(f"\nInput: {' '.join(tokens)}\n")
result = parser.parse(tokens)
parser.visualize_table(result)
parser.print_parse_trace(result)
if __name__ == "__main__":
example_1_simple_sentences()
example_2_arithmetic()
example_3_balanced_parentheses()
example_4_complex_analysis()
print("\n" + "=" * 100)
print("ALGORITHM SUMMARY")
print("=" * 100)
print("""
CYK Algorithm Steps:
1. Initialize: table[i][0] = non-terminals generating token[i]
2. For each span length j from 1 to n-1:
For each position i from 0 to n-j:
For each split k from 0 to j-1:
For each rule A → BC:
If B ∈ table[i][k] and C ∈ table[i+k+1][j-k-1]:
Add A to table[i][j]
3. Accept if S ∈ table[0][n-1]
Time Complexity: O(n³ · |G|)
Space Complexity: O(n²)
Where:
n = length of input string
|G| = size of grammar
""")
print("=" * 100)
Key Features:
1. Data Structures:
CNFGrammar: Stores terminal and non-terminal rules efficiently
CYKParser: Implements the core algorithm
ParseResult: Captures parsing results
2. Algorithm Implementation:
Base case: Fill diagonal with terminal productions
Iterative case: Build larger substrings from smaller ones
O(n³ · |G|) time complexity
3. Visualization:
visualize_table(): Clear table format
print_parse_trace(): Step-by-step trace
Shows which non-terminals derive each substring
4. Examples Included:
Natural language parsing
Arithmetic expressions
Balanced parentheses
Detailed trace analysis
The implementation handles all edge cases and provides clear output showing how the algorithm fills the DP table!