def rreverse(s):
if s == "":
return s
else:
return rreverse(s[1:]) + s[0]
(Very few people do heavy recursive processing in Python, the language wasn't designed for it.)
Answer from Fred Foo on Stack Overflowdef rreverse(s):
if s == "":
return s
else:
return rreverse(s[1:]) + s[0]
(Very few people do heavy recursive processing in Python, the language wasn't designed for it.)
To solve a problem recursively, find a trivial case that is easy to solve, and figure out how to get to that trivial case by breaking the problem down into simpler and simpler versions of itself.
What is the first thing you do in reversing a string? Literally the first thing? You get the last character of the string, right?
So the reverse of a string is the last character, followed by the reverse of everything but the last character, which is where the recursion comes in. The last character of a string can be written as x[-1] while everything but the last character is x[:-1].
Now, how do you "bottom out"? That is, what is the trivial case you can solve without recursion? One answer is the one-character string, which is the same forward and reversed. So if you get a one-character string, you are done.
But the empty string is even more trivial, and someone might actually pass that in to your function, so we should probably use that instead. A one-character string can, after all, also be broken down into the last character and everything but the last character; it's just that everything but the last character is the empty string. So if we handle the empty string by just returning it, we're set.
Put it all together and you get:
def backward(text):
if text == "":
return text
else:
return text[-1] + backward(text[:-1])
Or in one line:
backward = lambda t: t[-1] + backward(t[:-1]) if t else t
As others have pointed out, this is not the way you would usually do this in Python. An iterative solution is going to be faster, and using slicing to do it is going to be faster still.
Additionally, Python imposes a limit on stack size, and there's no tail call optimization, so a recursive solution would be limited to reversing strings of only about a thousand characters. You can increase Python's stack size, but there would still be a fixed limit, while other solutions can always handle a string of any length.
Videos
you need to print the return
so reverse(initial_input) is assigned to the returned value but if you wanted it printed you need to do `print reverse(initial_input)
since you cant change the last three you should print withing the function instead of returning it. your instuctor probably wanted you to do this to show the recursion
Here ya go try this its a little more complicated but it reverses in the function:
def reverse(text):
lst = []
for i in range(0,len(text)):
lst.append(text[len(text)-(i+1)])
lst = ''.join(lst)
print lst
print "Please enter the string you want to reverse: "
initial_input = raw_input()
reverse(initial_input)
Sounds like you just need to print the reversed string in the function? Did you instructor provide an actual example of what the output should look like?
Perhaps you should define a separate function to do the reverse, and have the reverse function simply call this new function, and print the result.
def actual_reverse(input_string):
if len(input_string) == 0:
return input_string
else:
return actual_reverse(input_string[1:]) + input_string[0]
def reverse(input_string):
print actual_reverse(input_string)
print "Please enter the string you want to reverse: "
initial_input = raw_input()
reverse(initial_input)
They are not adding up immediately until recursion reaches to final expression. Here, what is happening on each step:
"5" + backwards("1234")
"5" + "4" + backwards("123")
"5" + "4" + "3" + backwards("12")
"5" + "4" + "3" + "2" + backwards("1")
"5" + "4" + "3" + "2" + "1" + backwards("")
"5" + "4" + "3" + "2" + "1" + ""
"54321"
Basically you are constructing a chain of return statements (aka call stack), they concatenate at the very end into "54321".
In above computation, I omitted return keywords. For e.g. "5" + "4" + backwards("123") looks like return "5" + (return "4" + backwards("123")) in reality.
You are correct in what text[-1] and text[:-1] give you. I think where you're getting tripped up is on the recursive aspect of it, which is the tricky part.
When you're working on recursive stuff it helps not to overthink it. I know that most of programming requires you to understand every little nuance of your code but recursion is different. If you try to think through a recursive function's call stack in your head you'll just get confused. Human brains aren't like computers. Our stacks can only get about three levels deep before we lose track.
So for this problem the way you want to think about it is something like this:
"To reverse a string, you simply take the last character and put it at the beginning of the reversified version of the remaining characters."
It seems like a nonsense statement because it's defined in terms of itself, but that's precisely what recursion is, a function that is defined in terms of itself.
So for you question, text[-1] gives you the last item in the list and text[:-1] give you the remaining characters.
As an example, if your list is [1, 2, 3, 4] then evaluating each recursive call would go something like this:
backwards([1, 2, 3, 4])
evaluates to
4 + backwards([1, 2, 3])
which evaluates to
4 + 3 + backwards[1, 2])
which evaluates to
4 + 3 + 2 + backwards([1])
which evaluates to
4 + 3 + 2 + 1
When I first answered this question, I thought the function you listed didn't work and you wanted one that did, so I threw one together real quick. When I wrote it, I literally typed out the quote I listed above into my text editor then wrote out the python code (which looks just like the one you have posted). I didn't step through each call in my head I just typed out the sentence then wrote some code that implemented that sentence.
Recursion takes some getting used to but once you kind of get how think recursively you can apply it to all kinds of problems.
Another example that might be a bit more straight forward would be a recursive function that sums up all the numbers in a list.
sum([1, 2, 3, 4]) => 10
So the statement for this would be
To sum a list, add the first item in the list to the sum of the remaining elements in the list.
The python would look like this:
def sum(a):
if len(a) == 0:
return 0
else:
return a[0] + sum(a[1:])