Hello,
I’d like to understand recursive functions. I have this example:
Write a recursive function that computes the reverse of a string. For example, reverse(“flow”) should return “wolf”. Reverse the substring starting at the second character then add the first character at the end. For example, to reverse “flow”, first reverse “low” to “wol”, then add the “f” at the end.
##
# Display the characters in a string in reverse order.
#
def main() :
inputStr = input("Enter a string: ")
print(reverse(inputStr))
## Reverse the characters in a string.
# @param string the string to reverse
# @returns a string holding the characters in the reverse order
#
def reverse(string) :
if string != "":
return string[len(string) - 1] + reverse(string[0 : len(string) - 1])
return ""
# Call the main function.
main()
I’d like to understand what happens in that return line with reverse. For example if the word is London, I thought it would return, for:
string[len(string) - 1] + reverse(string[0 : len(string) - 1])
N + LONDO
But if I add a print line after the return, it shows something else:
Enter a string: London
L
oL
L
noL
L
oL
L
dnoL
L
oL
L
noL
L
oL
L
odnoL
L
oL
L
noL
...
Etc
So not sure what’s going on. How would you do the hand tracing?
Also, why does return " " mean? I couldn’t find that.
Thanks!(edited)
Thanks!