0

How to reverse a word using recursion in python?

Let say you are to impliment a recursive function to reverse a string eg text = 'sololearn' reverse_text(text) Results: nraelolos

7th Jan 2020, 6:13 PM
Vuyisile Lucas Ncipha
Vuyisile Lucas Ncipha - avatar
6 Réponses
+ 5
def reverse_text(text): return text[-1] + reverse_text(text[:-1]) if text else '' text = 'sololearn' print(reverse_text(text)) #but why do you need recursion if you can do this: print(text[::-1])
7th Jan 2020, 7:04 PM
Игорь Яковенко
Игорь Яковенко - avatar
+ 3
Your attempt ?
7th Jan 2020, 6:18 PM
Aymane Boukrouh
Aymane Boukrouh - avatar
+ 2
Vuyisile Lucas Ncipha please don't ask for answers next time unless you have tried. And post your attempt too, so we can take a look at it, and fix any errors you got. Игорь Яковенко try to ask for attempts fîrst next time, because giving the correct answer immedialy is not a good practice.
8th Jan 2020, 5:26 AM
Aymane Boukrouh
Aymane Boukrouh - avatar
0
Игорь Яковенко I wanted to understand the recursion for strings. I just find out from your example, string slicing is the key to accomplish this. Now I can implement this in c#, Java, and Javascript. Thanks for your example.
8th Jan 2020, 5:22 AM
Vuyisile Lucas Ncipha
Vuyisile Lucas Ncipha - avatar
0
Aymane Boukrouh [INACTIVE] my implementations are slightly different to his solution. The thing is I wanted to understand the solution. https://code.sololearn.com/ctb40epUJ5fR/?ref=app https://code.sololearn.com/cIpagzv22Z6T/?ref=app
8th Jan 2020, 6:07 AM
Vuyisile Lucas Ncipha
Vuyisile Lucas Ncipha - avatar