I need to reverse a string using recursion, I was able to accidentally write a code that successfully accomplishes the task, but I don't really understand why. Here's what I have
import stdio
import sys
# Entry point
def main():
s = sys.argv[1]
stdio.writeln(_reverse(s))
# Returns the reverse of the string s.
def _reverse(s):
# Base case: if s is the empty string, return an empty string.
if len(s) == 0:
return ""
# Recursive step: return last character in s + _reverse(s excluding last character).
else:
return s[-1] + _reverse(s[:len(s)-1])
if __name__ == '__main__':
main()
This makes sense to me just for the first recursive call. Lets say the input is "Bolton" the length of this string is 6, the first recursive call would simply call the _reverse function on s [0:5] What I don't understand is that how do the next recursive calls work? Because len(s) would remain the same? To my understanding, each recursive call to the _reverse() would subtract 1 from len(s) -- which is 6. Can someone please explain why thats not the case? How does the the len decrement?
_reverse()has its own private value ofs, each of which has a different length.