Discord Server Red Security Twitter Donation to Red Security Red Security Youtube Channel Red Security Tumblr Profile
Login or Register to Hide ads and Accessing all features on the forum

Tutorial 

Reverse a string using recursion (Python)

0 Replies, 960 Views

[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"
Love me like you do Heart
(This post was last modified: 05-21-2022, 09:23 PM by Covid-19.)

Possibly Related Threads…
Thread Author Replies Views Last Post
  Tutorial Doubly Linked List in Python Covid-19 0 2,247 07-30-2022, 09:15 PM
Last Post: Covid-19
  Tutorial Linked List in Python Covid-19 2 2,638 07-30-2022, 08:25 PM
Last Post: Covid-19
  Tutorial File Handling in Python Covid-19 2 2,672 06-16-2022, 06:17 PM
Last Post: Covid-19
  Tutorial Exceptions in Python Covid-19 0 1,843 06-08-2022, 09:19 PM
Last Post: Covid-19
  Free Automate the boring stuff with Python Covid-19 0 1,607 06-07-2022, 06:58 PM
Last Post: Covid-19
  Tutorial Turtle in Python Covid-19 0 1,841 06-02-2022, 10:14 PM
Last Post: Covid-19
  Tutorial Python 3.5: Class Methods Covid-19 0 1,792 05-29-2022, 01:07 PM
Last Post: Covid-19
  Tutorial Python 3.2: Inheritance in Python Covid-19 2 2,833 05-27-2022, 06:47 PM
Last Post: Covid-19
  Tutorial Python 3.4: Encapsulation and Abstraction Covid-19 0 1,825 05-27-2022, 06:45 PM
Last Post: Covid-19
  Tutorial Python 3.3: Operator Overloading Covid-19 2 2,827 05-26-2022, 08:50 PM
Last Post: Covid-19



Users browsing this thread: 1 Guest(s)