0% found this document useful (0 votes)
10 views4 pages

Context-Free Grammars Worksheet Solutions

Uploaded by

tarekmig
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views4 pages

Context-Free Grammars Worksheet Solutions

Uploaded by

tarekmig
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

CS-1301315 Theory of Computation

Worksheet-6 Solution:
Context Free Grammars
Dr Mohammed Khader

OBJECTIVES:
 Understand how context-free grammars (CFG) generate context-free languages.
 Understand ambiguity in CFG and how to remove it.
 Practice how to trace the CYK algorithm to derive a string from a CFG.

Q1. Find the language generated by the grammar G = ({S}, {a, b}, S, P).
P: S → aS | λ

L = { an : n ≥ 0 }

Q2. Find the language generated by the grammar G = ({S}, {a, b}, S, P).
P: S → aS | a

L = { an : n ≥ 1 }

Q3. Find the language generated by the grammar G = ({S}, {a, b}, S, P).
P: S → aS | bS | λ

L = { w ∈ {a, b}* }; i.e. all possible strings on {a, b}

Q4. Find the language generated by the grammar G = ({S}, {a, b}, S, P).
P: S → aSb | b

L = { anbn+1 : n ≥ 0 }

Q5. Find the language generated by the grammar G = ({S}, {a, b}, S, P).
P: S → aSbb | λ

L = { anb2n : n ≥ 0 }

Q6. Find the language generated by the grammar G = ({S, A, B}, {a, b}, S, P).
P: S → AB, A → aA | a, B → bB | b

L = { anbm : n, m ≥ 1 }

Q7. Find the language generated by the grammar G = ({S}, {a, b}, S, P).
P: S → aSa | bSb | b

L = { wbwR : w ∈ {a, b}*}


Q8. Find the language generated by the grammar G = ({S, A}, {a, b}, S, P).
P: S → aAb, A → aA | bA | λ

L = { awb : w ∈ {a, b}*}

Q9. Find the language generated by the grammar G = ({S, A, B}, {a, b}, S, P).
P: S → AAB, A → a | b, B → aB | bB | λ

L = { |w| ≥ 2 : w ∈ {a, b}*}; i.e. strings of length 2 or more on {a, b}

Q10. Find the language generated by the grammar G = ({S, A}, {a, b}, S, P).
P: S → AAS | λ, A → a | b

L = { |w| = 2k, k ≥ 0 : w ∈ {a, b}*}; strings of even length on {a, b}

Q11. Find the CFG for the following language:

L= {anbmcma2n: n,m>=0}
Solution:
P: S → aSaa| B
B → bSc | λ

Q12. Find the CFG for the following language:

L= {a2nbnakcma2m: n,m>=0, k>0}


Solution:
P: S → ABC
A → aaAb | λ
B → aB | a
C → cCaa | λ

Q13. Find the CFG for the following language:

L= {a2nbk+n+2mck: n,m>0, k>=0}


Solution:
P: S → ABC
A → aaAb | aab
B → bbB | bb
C → bCc | λ
Q11. Consider the following grammar:
G = ({S, A, B}, {a, b}, S, P)
P: S → AB | aaB
A → Aa | a
B→b
A- Show that the grammar G is ambiguous by deriving 2 different derivation trees.
First, we need to find a string with two different derivation trees. Choose 'aab'.
S S
A B a a B
A a b b
a
derivation tree 1 derivation tree 2

B- Show that the grammar G is ambiguous by finding 2 different left most derivations for string ‘aab’.
S=>AB=>AaB=>aaB=>aab
S=>aaB=>aab

C- Show that the grammar G is ambiguous by finding 2 different right most derivations for
string ‘aab’.
S=>AB=>Ab=>Aab=>aab
S=>aaB=>aab

Q12. Show that the grammar G is ambiguous. (Hint: derive 1+2*3)


G = ({E}, {+, *, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, E, P)
P: E → E + E | E * E | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9

AE E
E + E E * E
1 E * E E + E 3

2 3 1 2

derivation tree 1 derivation tree 2


You can show that by having 2 distinct LMD or 2 distinct RMD.
Another solution: 2 distinct LMD for 1+2*3:
E=> E+E=>1+E=>1+E*E=>1+2*E=>1+2*3
E=> E*E=>E+E*E=>1+E*E=>1+2*E=>1+2*3

Another solution: 2 distinct RMD for 1+2*3:


E=> E+E=>E+E*E=>E+E*3=>E+2*3=>1+2*3
E=> E*E=>E*3=E+E*3=>E+2*3=>1+2*3
Q13. Show that the grammar G is ambiguous. (Hint: derive 'abb')
G = ({S}, {a, b}, S, P)
P: S → aSb | Sb | λ

S S
a S b S b
S b a S b
λ λ
derivation tree 1 derivation tree 2

Q14. Which of the following grammar is a Simple grammar (S-Grammar)?


A- G1: S aAB| bA
AaA | bB | a

B- G2: S aSS | bAS| aA


AaA|b
C- G3: S aSA | bSS | cA
A  aA|bA| d

Answer: C

Common questions

Powered by AI

The CFG G generates the language L = { wbw^R : w ∈ {a, b}* }, which includes palindromic strings that start and end with 'b' with a mirrored structure around the middle 'b'. This language is significant because it illustrates the use of CFG to capture symmetry in strings, a common trait in many practical applications such as syntax patterns in natural language processing or DNA sequence symmetry in genomics. This CFG efficiently captures the recursive and reflective nature of such structures by ensuring every production adds a pattern around the central axis, demonstrating the power of CFGs to formalize naturally recurring patterns.

An example of an ambiguous context-free grammar is one where the grammar for arithmetic expressions lacks operator precedence, for instance, G = ({E}, {+, *, 0, 1, 2}, E, P) with productions such as P: E → E + E | E * E | 0 | 1 | 2. For the expression '1+2*3', ambiguity arises in parse tree derivations where '+' and '*' operations can occur in differing hierarchical orders without explicit precedence. To structure the CFG to prevent this ambiguity, the grammar can be refactored to explicitly account for operator precedence by creating separate non-terminals for different operator levels, such as 'Expression', 'Term', and 'Factor'. Productions can then enforce precedence hierarchies, with '+' being lower precedence than '*', by decomposing the expression into sub-expressions: E → E + T | T and T → T * F | F, where F is a terminal number like 0, 1, 2. This structuring enforces a strict precedence and left-associative structure, eliminating ambiguity in parsing operations.

The production rule S → AAS | λ in the CFG ensures the generation of strings of even length by adding pairs of non-terminal symbols 'A' each time it expands. Every application of the rule S → AAS introduces two 'A' which, through subsequent production expansion, can each result in a terminal 'a' or 'b'. Hence, each application increases the length of the resulting string by 2. The use of the empty string λ allows for the grammar to generate a base case of zero length, maintaining the invariant of even length through mathematical induction. Thus, the structure ensures that only strings where the sum of all generated terminal symbols is even can be derived.

A 'Simple Grammar' or S-Grammar is characterized by having productions where each production's right side has at most one non-terminal symbol, meaning it tends towards linear production expansion. In the provided options, grammar G3: S → aSA | bSS | cA; A → aA|bA| d fits this definition. This is because its production involves straightforward expansions that do not allow for complex hierarchical branching typical of more generalized CFGs. It captures the essence of a straightforward derivation sequence that does not introduce multiple new non-terminals in a single production, making it simple to parse.

The grammar G with the production P: S → aS | λ generates the language L = { a^n : n ≥ 0 }, meaning it generates strings composed of any number of 'a's including the empty string. The inclusion of lambda (λ) allows for the generation of the empty string, which is a crucial part of enabling the language to include strings of zero length. Without λ, the language could only generate non-empty strings of 'a's, specifically strings of at least one 'a'. The lambda provides the flexibility needed to generate a broader set of strings and is essential for defining languages that include the empty string.

Chomsky Normal Form (CNF) is significant in the context of context-free grammars because it provides a standardized structure for grammars. In CNF, every production rule is simplified into either two non-terminal symbols or a single terminal symbol. This standardized form is particularly relevant to algorithms like the CYK algorithm as it relies on this structure to efficiently parse strings. The uniformity of rule structure in CNF makes it easier to handle grammatically correct strings computationally, allowing the CYK algorithm to systematically and reliably determine membership in the language. CNF thus enhances algorithmic access and functionality by simplifying the parsing process through a predictable pattern of production expansion.

To remove ambiguity from the grammar G, which causes multiple derivation trees for the string 'aab', steps involve rewriting the grammar to enforce precedence and associativity explicitly. First, identify where ambiguity arises: in this case, S can derive 'aab' in different sequences due to the options for expending 'A' and concatenating with 'B'. A possible approach is to refactor the grammar to ensure only one left-most (or right-most) derivation is valid for all strings. This can involve introducing new non-terminal entities to separate different types of expressions or derivations primarily around 'A' and 'B'. Ensure any refactoring takes arithmetic operation precedence and associativity into account, perhaps by creating new rules that separate additive and multiplicative identities if the operations support such. This makes each derivation deterministic, eliminating the multiple valid left-most/right-most derivations for single strings. Alternative approaches might include semantic actions or global constraints that apply during parsing.

Ambiguity in context-free grammars presents significant challenges in parsing as it leads to the possibility of generating multiple valid parse trees or derivations for the same string. This ambiguity complicates understanding the intended hierarchical structure of languages, leading to difficulties in processing and interpreting the data correctly, such as in the case of programming languages or arithmetic expressions lacking operator precedence. Strategies to mitigate these challenges include: rewriting ambiguous grammars to eliminate conflicts by removing non-essential derivation paths, using additional semantic information during parsing to prioritize certain derivations, or employing parsing strategies that enforce deterministic or precedence-based parsing (such as using SLR or LALR parsers). Another approach is to use semantic action rules that help the parser choose between ambiguous parses based on context or additional knowledge beyond the syntax alone.

The Cocke-Younger-Kasami (CYK) algorithm is a parsing algorithm for context-free grammars in Chomsky Normal Form. It is used to determine if a string belongs to a language generated by a CFG. The algorithm works by filling out a table where each cell contains non-terminal symbols that can generate the substring of the input string corresponding to that cell. The algorithm proceeds bottom-up, starting with substrings of length 1 (single characters) and building up to the full string. For each substring, it combines results from possible splits and checks if they can be derived together from the grammar's productions. If the start symbol is in the topmost cell of the table after processing the whole string, the string is a member of the language; otherwise, it is not. CYK is particularly useful because it systematically checks all possibilities, making it a robust tool for membership testing and syntax checking.

The grammar is considered ambiguous because it can generate the same expression with multiple distinct parse trees or derivation sequences. For the expression '1+2*3', there can be different derivation paths that change the order of operations interpreted, resulting in two possible interpretations: either +(1, *(2, 3)) or *(+(1, 2), 3). The two different left-most derivations (LMD) and right-most derivations (RMD) exhibit this ambiguity. Different parse trees represent different order of operations (order of evaluation), which is significant in expressions involving operations like '+' and '*', which have different precedence. This ambiguity indicates that the grammar lacks precedence rules to enforce a consistent syntax tree structure for arithmetic expressions.

You might also like