LearnFrenzy
Sign in Take a free test

Recursion · Find the Error · Question 5

Bug: the "reversed" string is unchanged Answer, explanation & discussion

  • Find the error
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 5 Back to Exercise

rev("abcd") should return "dcba". Which statement correctly identifies the bug?

main.py
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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links