Compsci 06, Spring 2011, Grammar FUN, April 6
Name____________________ net-id _________
Name____________________ net-id _________
Name____________________ net-id _________
These questions are about the code in
SimpleGrammar.py, some code
reproduced below.
- Which is the best explanation of the body of code
in the statement
if
w.startswith("<")
in the function
expand
below:
def expand(sentence,rules):
sent = ""
for w in sentence.split():
if w.startswith("<"):
chosen = random.choice(rules[w])
sent += expand(chosen,rules) +" "
else:
sent += w + " "
return sent.strip()
- the rule chosen as a replacement for
w
may require
expansion because it has tags in it, so the rule
is passed to expand
in case it's more than a simple word.
- because the word
w
starts with a < symbol we
know a choice should be made to replace it, but the line
assigning to sent
could be replaced with:
sent += chosen + " "
- the parameter
rules
is a dictionary, accessing
the dictionary generates a random replacement for the key w
and that replacement also starts with a < symbol.
- Which is the best explanation of why
sent.strip()
is
returned rather than simply sent
?
- all strings must be stripped in Python to ensure they can
be printed.
- The string has an extra space at the end because a space is
always the last thing concatenated to
sent
in
the for-loop.
- All white-space should be removed from
sent
, not
just leading and trailing white-space.
- If we want a combined-color like yellow-green or
blue-red to be a possible color which string shuld be added
to the list
colors
in the function
create_content
?
- "<color> - <color>"
- "yellow-green"
- "yellow - <color>"
These questions refer to
Sierpinsk1.py which generates
a Sierpinski gasket.
- What is the type of parameters
p1
, p2
and
p3
to the function sierpinski
:
- string
- list
- tuple
- What ensures that the recursive function
sierpinski
will eventually terminate, i.e., stop generating recursive
calls?
- lines cannot be drawn that are smaller than the screen's
resolution, eventually no lines will be drawn
- The value of
parmeter
level
decreases in each recursive call, eventually
reaching 0 when no calls are made.
- The computer will run out of
memory if too many recursive calls are made.
- Which is the best characterization of the function
chaos
?
- it is recursive, and not iterative
- it is iterative, and not recursive
- it is both iterative and recursive
These questions refer to
Koch.py which generates
a Koch Snowflake.
- Which is the best characterization of the function
draw
?
- it is recursive, and not iterative
- it is iterative, and not recursive
- it is both iterative and recursive
-
In function
draw
if the value of parameter iters
is 1, what will the length
of string flake
be after the first for-loop?
- 18
- 23
- 28
- If the value of
iters
is 4 what will the length
of flake
be?
- below 100
- between 100 and 500
- more than 500