Professional Documents
Culture Documents
solution: Definitions.
S0 → S0 c|A0 L0 = {ai bj ck |i = j}
A0 → aA0 b|
2. Write down a single grammar that works for _all_ the following sentences:
(a) I saw a boy with a telescope
(b) I saw boys with girls
(c) I eat sushi with tuna
Solution:
S → NP VP
NP → N | D N | NP PP
VP → V NP | VP PP [∗]
PP → P NP
N → I | boy | telescope | boys | girls | sushi | tuna
V → saw | eat
P → with
D→a
NP VP
N
VP PP
I
V NP P NP
saw D N with D N
a boy a telescope
S
NP VP
N
V NP
I
saw
NP PP
D N P NP
a boy with D N
a telescope
Cont.
CS 321 Homework 7 Page 3 of 6
NP VP
N V NP
I saw NP PP
N P NP
boys with N
girls
S
NP VP
N
VP PP
I
V NP P NP
saw N with N
boys girls
NP VP
N V NP
I eat NP PP
N P NP
sushi with N
tuna
S
NP VP
N
VP PP
I
V NP P NP
eat N with N
sushi tuna
Cont.
CS 321 Homework 7 Page 4 of 6
3. Now write two unambiguous grammars for the above problem, one with the PP modifying NP,
and one with the PP modifying VP.
Solution:
G0 (PP modifying NP) : replace [*] with VP → V NP.
G1 (PP modifying VP) : replace [*] with
VP → VP’ PP
VP’ → V NP
4. Give an example of ambiguous language. Write a CFG for it and demonstrate why it is ambiguous.
Solution:
See question 1(f). s = abc is ambiguous under the grammar since s ∈ L0 and s ∈ L1 .
S ⇒ S0 ⇒ S0 c ⇒ A0 c ⇒ aA0 bc ⇒ abc
S ⇒ S1 ⇒ aS1 ⇒ aA1 ⇒ abA1 c ⇒ abc
5. Write a CFG for the language over {a,b} which has same number of a’s as b’s.
Is this CFG ambiguous? Justify.
Solution:
S → aSb | bSa | SS |
It is ambiguous. Choose s = ,
S⇒S⇒
S ⇒ SS ⇒ S ⇒
6. Write a CFG for {a^m b^n | m != n, and m,n >= 0 }.
Solution:
S0 → A | B
A → aA | aS
B → Bb | Sb
S → | aSb
7. Write a CFG for {a^n b^n a^m b^m | m,n >= 1} \cup {a^n b^m a^m b^n | m,n >= 1 }.
If your grammar is ambiguous, prove it.
What about we replace the \cup with \cap?
Solution:
∪ (Note that m, n ≥ 1, not 0)
S → S0 | S1
S0 → W W
W → aW b | ab
S1 → aT b | aS1 b
T → bT a | ba
Cont.
CS 321 Homework 7 Page 5 of 6
b
start A B
a
b a
S0 → | A
A → b | bA | a | aB
B → aC | b | bA
C → b | bA
S → | C0 C0 | C1 C1 | C0 U | C1 V
S1 → C0 C0 | C1 C1 | C0 U | C1 V
U → S1 C0
V → S1 C1
C0 → 0
C1 → 1
∀s ∈
/ LC (copy language), discuss two cases.
Cont.
CS 321 Homework 7 Page 6 of 6
s∈
/ LC
⇒ ∃j, s.t. 0 ≤ j < p, cj 6= c0j , i.e. {cj , c0j } = {0, 1}
⇒ s1 ∈ L(W0 ), s2 ∈ L(W1 ), where s = s1 s2 , |s1 | = 2j + 1, {W0 , W1 } = {A, B}
⇒ s ∈ L(S).
Solution:
(A) String with odd length that any character with even/odd index must be b/a.
Regular. Regular expression: b(ab)∗ .
S → bB | b
B → aS
(B) String that copies a random string as the first half, reverse it then make a reversion on every character
as the second half.
Not regular. (pump s = ap bp )
(C) String with odd number of a and every b is on the right side of some a.
Regular. Regular expression: (a|ab)((a|ab)(a|ab))∗ .
S → aA | a
A → aC | bB | b
B → aC
C → aA | a | bD
D → aA | a
The End.