CSCI 301 L27 Worksheet

Lecture 27 - Exercises

Part A - Context-Free Grammars

Grammar 1: \(\Sigma = \{a, b\}, V = \{S\}, S = S\) \[ \begin{align*} S &\rightarrow \epsilon\\ S &\rightarrow aSa\\ S &\rightarrow bSb \end{align*} \]

  1. Give a derivation for \(abba\) in Grammar 1.
  2. Describe the language of Grammar 1.
  3. Draw the parse tree for your derivation from #1.

Grammar 2: \(\Sigma = \{a, b\}, V = \{S\}, S = S\) \[ \begin{align*} S &\rightarrow \epsilon\\ S &\rightarrow aSbS\\ S &\rightarrow bSaS\\ \end{align*} \]

  1. Give a derivation for \(baabba\) in Grammar 2.

  2. Describe the language of Grammar 2.

  3. Draw the parse tree for your derivation from #4.

  4. A palindrome is a string that is equal to itself when reversed. Find a context-free grammar for the language of even-length palindromes over the alphabet \(\{a, b\}\).

Part B - Leftmost, Rightmost Derivations

  1. Give a leftmost derivation of \(abab\) in Grammar 2 above.
  2. Give a rightmost derivation of \(abab\) in Grammar 2 above.
  3. Are their parse trees the same?

Part C - Ambiguous Grammars

  1. Show that Grammar 2 above is ambiguous by finding more than one left-most derivation for the string \(abaabb\).

Part D - More

  1. Describe the language represented by the grammar \(S \rightarrow aSa \mid bSb \mid \epsilon\)
  2. Find a context-free grammar for each of the following languages:
    1. \(\{a^nb^n: n \in \mathbb{N}\}\)
    2. \((01)^*\)
    3. \(\{a^{2n}b^n : n \in \mathbb{N} \cup \{0\}\}\)
    4. \(0^*1^*\)
    5. The language of properly nested parentheses. For example, this language would contain \(\epsilon, (), (()), ()(), (()())\), and \(()(())\), but not \()(, (, (()\), or \(())(()\).