CS143 Midterm Exam SOLUTIONS (April 30, 2015)
CS143 Midterm Exam SOLUTIONS (April 30, 2015)
CS143 Midterm Exam SOLUTIONS (April 30, 2015)
1. (10 points)
For the alphabet {0, 1}, give a regular expression and draw a DFA for the set of all strings in
which each 1 is preceded by one or more 0’s (but not necessarily immediately preceded ), and
the number of “01” substrings appearing in the string is even (note: 01110111000 is in this
language).
Regular expression
(0+ 1+ 0+ 1+ )∗ 0∗
DFA
2. (5 points) Draw a line through each useless production in the following grammar (hint:
find the useful productions and symbols first.) Note: “Useless” has a specific mathematical
definition that was presented in the lecture and notes.
S → AB
S → S
S → BB
A → BC
A → aAc
B → AB
B → aBb
B →
C → AB
1
3. (15 points)
Compute the FNE, Follow, and First sets for the nonterminals of the context-free grammar
below, and write them in the spaces provided. Also, answer the questions about the grammar.
Is the grammar LL(1) [answer without building the LL(1) parse table]? Yes No
(explain briefly below)
Answer: Consider the parse tree for the single string “a”. We don’t know if the first or
second A should expand to the ’a’, so the grammar is ambiguous. Ambiguous grammars
cannot be LL(1).
Note: Many students claimed that because the grammar is regular that it was LL(1). For
any regular language there exists a grammar that is LL(1), but that doesn’t mean that every
grammar for that language is LL(1).
4. (10 points) Left factor and eliminate immediate left recursion in the following CFG:
S → Sa
S → bS
S → Sc
S → bbA
A → f
2
5. (10 points) Below is an SLR(1) parse table (ACTION and GOTO tables) for a context-free
grammar. Next to it is a table giving the length of the right-hand side for each production
in the grammar.
(a) Show the sequence of stacks and inputs when parsing “abad”. Stacks should just contain
state numbers (and $). (The lectures showed stacks with states and symbols underneath
them. Don’t list the symbols.)
$0 abad$ $02345 $
$07 bad$ $023 $
$02 bad$ $01 $
$026 ad$ accept
$023 ad$
$0234 d$
$02345 $
Note: Some people wrote an error at the end of the parse because after reducing using
production 0, there’s no GOTO entry for S 0 . Techincally this is correct, but the r0
action should just be accept, so that’s what is written here.
(b) What is the context-free grammar from which the table was generated?
S → AB
A → dAd
A → a
B → Bad
B → b