Beruflich Dokumente
Kultur Dokumente
Give parse trees and leftmost derivations for the following strings.
1. a
2. a*(a+a)
3. a+a+a
4. ((a+(a)))
Solution We present the leftmost derivations below.
1. S E T F a.
2. S E T T F F F a F a (E) a (E + T ) a (T + T ) a (F + T )
a (a + T ) a (a + F ) a (a + a)
3. S E + T E + T + T T + T + T T + T + T F + T + T a + T + T a + F + T
a+a+T a+a+F a+a+T a+a+a
4. S T F (E) (T ) (F ) ((E)) ((E + T )) ((T + T )) ((F + T ))
((a + T )) ((a + F )) ((a + (E))) ((a + (T ))) ((a + (F ))) ((a + (a)))
Exercise 2 Answer each part for the following context-free grammar.
R
S
T
X
XRX | S
aT b | bT a
XT X | X |
a|b
1. What are the variables and terminals of G? Which is the start symbol? (The set of variables
is {R, S, X, T } and the set of terminals is {a, b}. R is the start symbol.)
2. Give three examples of strings in L(G). (ab, ba, aab)
3. Give three examples of strings not in L(G). (a, b, aa)
1
4. Here is a context-free grammar for L = {w | the length of w is odd and its middle is 0}:
S 0S0 | 0S1 | 1S0 | 1S1 | 0
5. Here is a context-free grammar for L = {w | w contains more 1s than 0s}:
S T S | 1T | 1S
T T T | 0T 1 | 1T 0 |
Note that T generates all words in which there are equal number of 1s and 0s. If a word w
contains more 1s that 0s, then w must be of one of the following forms.
w = 1w1 such that w1 contains more 1s than 0s.
w = 1w1 such that w1 contains equal number of 1s and 0s.
w = w1 w2 such that w1 contains equal number of 1s and 0s and w2 contains more 1s
than 0s.
6. Here is a context-free grammar for L = {w | w is a palindrome, i.e., w = wR }:
S 0S0 | 1S1 | 0 | 1 |
7. Here is a context-free grammar for the empty set:
S S
Exercise 4 Please convert the following CFG into an equivalent CFG in Chomsky normal form,
using the procedure given in Theorem 2.6.
A BAB | ABA | B |
B 00 |
Solution We introduce a new start symbol S and obtain the following CFG.
S A
A BAB | ABA | B |
B 00 |
After -rule elimination, we generate the following CFG.
S A|
A BAB | ABA | B | BA | AB | AA | BB
B 00
After unit rule elimination, we generate the following CFG.
S BAB | ABA | BA | AB | AA | BB | 00 |
A BAB | ABA | BA | AB | AA | BB | 00
B 00
BU | AV | BA | AB | AA | BB | W W |
BU | AV | BA | AB | AA | BB | W W
WW
AB
BA
0