Worksheet6 - CFG_solution
Worksheet6 - CFG_solution
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 | λ
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
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 | λ
Q10. Find the language generated by the grammar G = ({S, A}, {a, b}, S, P).
P: S → AAS | λ, A → a | b
L= {anbmcma2n: n,m>=0}
Solution:
P: S → aSaa| B
B → bSc | λ
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
AE E
E + E E * E
1 E * E E + E 3
2 3 1 2
S S
a S b S b
S b a S b
λ λ
derivation tree 1 derivation tree 2
Answer: C