Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Akash malhotra
3,025 PointsReverse string using recursion
I'm trying to reverse a basic string using recursion in pyhon. I get an error "RuntimeError: maximum recursion depth exceeded".What's wrong with my method, the logic seems fine to me.
def reverse(t):
return reverse(t[1:])+t[0]
print(reverse('hello world'))
2 Answers
Stone Preston
42,016 PointsYou need to check if t is empty first
def reverse(t):
if t == "":
return t
else:
return reverse(t[1:]) + t[0]
print(reverse('hello world'))
Solution found here
Caleb Kleveter
Treehouse Moderator 37,862 PointsIs the reason is you can't reverse a empty string? I'm having trouble understanding the function, but that might be why.
Akash malhotra
3,025 PointsSo If I'm understanding this right, this is how recursion is working right? ( I'm just using 'hello' instead of 'hello world')
= reverse(ello) + h # The recursive step
= reverse(llo) + e + h
= reverse(lo) + l + e + h
= reverse(o) + l + l + e + h # Base case
= o + l + l + e + h
= olleh
Caleb Kleveter
Treehouse Moderator 37,862 PointsI'm not sure, I don't know to much python, or recursion.
Akash malhotra
3,025 PointsAkash malhotra
3,025 PointsCan you explain why that is neccesary? Like I understand that it's good to check,but why can't we just return it, assuming that 't' is not empty.
Stone Preston
42,016 PointsStone Preston
42,016 PointsHonestly im not too sure. Dont use recursion much. I added some print calls to see what it actually looks like as it goes through the string:
and got
so it looks like the empty string at the end causes the function to get stuck in a recursive loop. the check provides a way to break out of the recursion