marto ndegz
marto ndegz

Reputation: 21

python stack method for reverse string code

I want to use the stack method to get reverse string in this revers question.
"Write a function revstring(mystr) that uses a stack to reverse the characters in a string."
This is my code.

from pythonds.basic.stack import Stack
def revstring(mystr):

    myStack = Stack()   //this is how i have myStack

    for ch in mystr:   //looping through characters in my string
        myStack.push(ch)   //push the characters to form a stack

        revstr = ''  //form an empty reverse string
        while not myStack.isEmpty():

            revstr = revstr + myStack.pop()  //adding my characters to the empty reverse string in reverse order
            return revstr

print revstring("martin")

the output seems to print out only the first letter of mystr that is "m" why this??

Upvotes: 2

Views: 5159

Answers (2)

BPL
BPL

Reputation: 9863

Here's 3 solutions to the same problem, just pick one:

1ST SOLUTION

Fixing your solution, you almost got it, you just need to indent properly your blocks like this:

from pythonds.basic.stack import Stack


def revstring(mystr):

    myStack = Stack() # this is how i have myStack

    for ch in mystr: # looping through characters in my string
        myStack.push(ch) # push the characters to form a stack

    revstr = '' # form an empty reverse string
    while not myStack.isEmpty():
        # adding my characters to the empty reverse string in reverse order
        revstr = revstr + myStack.pop()

    return revstr

print revstring("martin")

2ND SOLUTION

This one is structurally the same than yours but instead of using a custom stack, it's just using the builtin python list

def revstring(mystr):

    myStack = [] # this is how i have myStack

    for ch in mystr:
        myStack.append(ch) # push the characters to form a stack

    revstr = '' # form an empty reverse string
    while len(myStack):
        # adding my characters to the empty reverse string in reverse order
        revstr = revstr + myStack.pop()

    return revstr

print revstring("martin")

3RD SOLUTION

To reverse strings, just use this pythonic way :)

print "martin"[::-1]

Upvotes: 3

Szabolcs Dombi
Szabolcs Dombi

Reputation: 5783

  • the while should not be in the for
  • the return should be outside, not in the while

code:

from pythonds.basic.stack import Stack

def revstring(mystr):

    myStack = Stack()      # this is how i have myStack

    for ch in mystr:       # looping through characters in my string
        myStack.push(ch)   # push the characters to form a stack

    revstr = ''            # form an empty reverse string
    while not myStack.isEmpty():
        # adding my characters to the empty reverse string in reverse order
        revstr = revstr + myStack.pop()

    return revstr


print revstring("martin")

Upvotes: 0

Related Questions