CSc 120: Recursion 03
Expected Behavior
Write a recursive function str2objects(spec)
that creates a list of Python objects based
on the contents of the string spec
. Example:
>>> str2objects("dict list str dict")
[{}, [], '', {}]
Assume that spec
contains only whitespace separated
occurrences of "dict"
, "list"
, and "str"
.
Your first thought might be to use a helper function or a default argument but perhaps
the following will inspire another way to approach the problem:
>>> "a b c".split(None,1)
['a', 'b c']
Programming Requirements
Solve this problem using recursion. You are allowed to use only
the following programming constructs:
-
if statements;
-
return statements;
-
assignment;
-
recursive function calls (if you use any helper functions
then these must all be recursive as well);
-
comparison operations (==, !=, etc.);
-
list indexing and slicing;
-
list concatenation/extension;
-
The
len()
built-in function;
-
The method
str.split()
.
Solutions that go outside these constructs, e.g., by
using for/while loops or list comprehensions,
will not get credit.
Examples
-
Call: str2objs("")
Result: []
-
Call: str2objs("dict")
Result: [{}]
-
Call: str2objs(" list dict ")
Result: [[],{}]
-
Call: str2objs("dict list str dict")
Result: [{},[],"",{}]