Question 38
What is the output of the following code?
Hint
f() seems to be a recursive function that acts on the contents and/or value of seq.
Solution
Inside f(),
- if
seqis an empty list, returnseq(whereseq = []) - else if
seqis not a list, return a new list containingseqinside it - else, return 2 times of the result of the recursive call to
f()containing the first element as the parameter, concatenated with the result of the recursive call tof()contianing a list of the rest of the elements
f(lst) = f([1, [2]])
= [f(1)]*2 + f([[2]])
= [1]*2 + f([[2]])
= [1, 1] + f([[2]])
= [1, 1] + [f([2])]*2 + f([])
= [1, 1] + [[f(2)]*2 + f([])]*2 + f([])
= [1, 1] + [[2]*2 + []]*2 + f([])
= [1, 1] + [[2, 2] + []]*2 + f([])
= [1, 1] + [[2, 2]]*2 + f([])
= [1, 1] + [[2, 2], [2, 2]] + f([])
= [1, 1] + [[2, 2], [2, 2]] + []
= [1, 1, [2, 2], [2, 2]]