This is a common interview question in many python basic or intermediate positions, where the interviewer asks to reverse a word using python code. I was playing with data structures and algorithms in Python while it came to my mind. This is a rudimentary implementation of stack in any language. A primary function of stack data structure in putting a new element on the top of a stack and removing it. If I want to get the first item of the stack, it is called Fist In First Out or FIFO and if I want the last item out of the stack, it is known as Last In First Out or LIFO.

The idea to reverse a word uses the LIFO concept of stack operation. So, we insert the word in a list, and then pop them out in LIFO fashion to get an inverted or reverse list. Below is the python string program to do the same.

I create a function which accepts a string and cast it to a list. I handle the exception if someone misses entering a string (which is an additional line and optional). I then loop through the length of the string to pop the contents of the list in reverse fashion (the pop itself is a reverse function, so the statement is for your understanding only.

def rev(str):
    spl = list(str)  # Type cast the string in a list
    i = len(spl)     # take the length of the string
    if i ==0:
        print('You have not entered a word!')
    while i!=0:
        print(spl.pop())
        i = i -1     # count down 

So, here is the output looks like –

rev
Output of reverse function

Hope this helps you. If you want to learn more about stack data structure, here is an useful link.

LEAVE A REPLY

Please enter your comment!
Please enter your name here