Question 5
Back to Exercise
rev("abcd") should return "dcba". Which statement correctly identifies the bug?
def rev(s):
if len(s) <= 1:
return s
return s[0] + rev(s[1:])
print(rev("abcd"))
- A The base case should be len(s) == 0
- B Slicing s[1:] removes the wrong character
- C The first character is put back in front; it must go after the reversed rest: rev(s[1:]) + s[0] Correct
- D Strings cannot be reversed recursively
Correct Answer: Option C
The order in which the parts are combined decides the result.
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!