244 views
2 2 votes

A function $\texttt{deep_map(f, s)}$ replaces every non-list element $\texttt{x}$ inside a nested list $\texttt{​​​​​​​s}$ with $\texttt{f(x)}$.

It modifies $\texttt{​​​​​​​s}$ in place, returns $\texttt{None}$, and should not create new nested lists.

Consider the following Python code:

s = [3, [1, [4, [1]]]]

s1 = s[1]
s2 = s1[1]
s3 = s2[1]

result = deep_map(lambda x: x + 1, s)

Which of the following statements are correct?

  1. result == [4, [2, [5, [2]]]]
  2. s == [4, [2, [5, [2]]]]
  3. result is None
  4. s1 is s[1] and s2 is s1[1] and s3 is s2[1]

2 Answers

0 0 votes
Answer can not be specified unless deep_map is defined. AI says its a part of a course at UCB, CS61A. But function definition will decide whether it works recursively or only at the first level, even if the name suggests recursive traversal till final depth. If it is assumed to be recursive, B,C and D are correct. else only C, D are correct.
0 0 votes

The function $\texttt{deep_map}$ modifies the original nested list in place.

Initially:

s = [3, [1, [4, [1]]]]

Applying $\texttt{lambda x: x + 1}$ to every non-list element gives:

3 becomes 4
1 becomes 2
4 becomes 5
1 becomes 2

So $\texttt{s}$ becomes:

[4, [2, [5, [2]]]]

Hence option B is correct.

Since $\texttt{deep_map}$ modifies in place and returns $\texttt{None}$, option C is also correct.

The function should not create new nested lists, so the old references $\texttt{s1}$, $\texttt{s2}$, and $\texttt{s3}$ should still point to the same inner lists.

Therefore, option D is correct.

Option A is incorrect because $\texttt{result}$ is $\texttt{None}$, not the modified list.

Correct Options: B, C and D

Answer:
Position:
Show:

Related questions

2 2 votes
3 3 answers
233
233 views
GO Classes asked Jul 2
233 views
A function $\texttt{shuffle(s)}$ takes a sequence $\texttt{s}$ with an even number of elements. It returns a new list by interleaving the first half of $\texttt{s}$ with ...
2 2 votes
3 3 answers
249
249 views
GO Classes asked Jul 2
249 views
Consider the following Python code:s = [6, 7, 8] print(s.append(6)) s.insert(0, 9) x = s.pop(1) s.remove(x) print(s)What is the output of the code above?None [9, 7, 8]Non...
2 2 votes
3 3 answers
184
184 views
GO Classes asked Jul 2
184 views
Consider the following Python code:s = [3] s.extend([4, 5]) s.extend([s.append(9), s.append(10)]) print(s)What is the output of the code above?[3, 4, 5, 9, 10][3, 4, 5, N...
2 2 votes
3 3 answers
208
208 views
GO Classes asked Jul 2
208 views
Consider the following Python code:s = [9, 7, 8] a, b = s, s[:] print(a is s, b == s, b is s) print(a.pop()) print(a + b)What is the output of the code above?True True Tr...