Red Security

Full Version: Reverse a string using recursion (Python)
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
[Image: BFMMlbcQvml9HSqXcvNp]
Reverse an string:
     Hi guys, I hope you all are doing well today. I have a problem for you guys and the name of this problem is Spelling backwards. We use a recursive approach to solve this problem. What we do in this program is to take a string from the user and then reverse it then write each character of that string in reverse order.

For Example if the string is

COVID

The output should be

D
I
V
O
C

Let’s see now how we can code this problem


Code:
def spell(txt):
    if len(txt)==1:
        print(txt)
    else:
        print(txt[-1])
        return spell(txt[:-1])


txt = input()
spell(txt)


Now let’s break down this code into steps and learn each step one by one
Quote:First step: def spell(txt):

In this step we are creating a function and passing a string ‘txt’ as an argument to it
Quote:Second step: if len(txt)==1:
    print(txt)

This is the base case and in case if user gives us a single character we just print this character as it is

The trick of each recursion is in else portion so now see
Quote:print(txt[-1])

This will print the last character of any string and then it will return the string without including the last character and this will repeat until the string becomes null.
Hope you understand this problem and if you have any question you can ask me directly. That’s it for now. till then



"Keep Good care of your Health
Allah Hafiz and Good Bye Till the next post"