0

Where is the break criteria in this recursive function? Why doesn't this go on endlessly reversive characters of the string?

print('Enter your input:')
n = input()

def reverse(s):
    if len(s) == 0:
        return s
    else:
        return reverse(s[1:]) + s[0]

print (reverse(n))

Enter your input:
Something
gnihtemoS

2 Answers 2

1

When the String is of length 0, you make a non-recursive return, causing the recursive calls on the stack to return until you get all the way to the bottom of them.

Sign up to request clarification or add additional context in comments.

Comments

0

A recursive function terminates if it satisfies two properties:

  • There must be a "base case" which is solved without any recursive calls, and
  • Each recursive call must be on an input which is "closer" to the base case than before.

In this recursive function, the base case is the empty string; it is handled by return s without making any recursive calls. The recursive call is on the string s[1:] which is one character shorter than s, so it is "closer" to the empty string. Therefore the function satisfies both of these properties, so it always terminates.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.