The Comedian
The Comedian

Reputation: 1

I am trying to use a stack to reverse the order of words in python

At the moment my program will print each letter of the word on a new line rather then the words themselves will post full programs below.

class Stack:
    def __init__(self):
        self.items = []

    def isEmpty(self):
        return self.items == []

    def push(self, item):
        self.items.append(item)

    def pop(self):
        return self.items.pop()

    def peek(self):
        return self.items[len(self.items)-1]

    def size(self):
        return len(self.items)

Here's the script where I import my Stack class and use reverseStr():

import Stack

def reverseStr(mystring):
    s=Stack.Stack()
    for word in mystring:
        s.push(word)
    while not s.isEmpty():
        print(s.pop(),)
        
    
def main():
    mystring = "my name is jon doe"
    reverseStr(mystring)

main()

Upvotes: 0

Views: 39

Answers (1)

ddejohn
ddejohn

Reputation: 8970

You need to split your string into words first, otherwise your string will be treated as a sequence of characters:

>>> reverseStr(mystring.split())
doe
jon
is
name
my

If you want to print the reversed words on the same line, you can use print(s.pop(), end=" "). Here's the result:

>>> reverseStr(mystring.split())
doe jon is name my

If instead, you want to actually return a new string with the words reversed, you can use the accumulator pattern:

def reverseStr(mystring):
    s = Stack.Stack()
    for word in mystring:
        s.push(word)
    reversed_words = []
    while not s.isEmpty():
        reversed_words.append(s.pop())
    return "".join(reversed_words)

Output:

>>> reverseStr(mystring.split())
'doe jon is name my'

Notice the quotation marks, meaning that the string wasn't printed but actually returned from your reverseStr function.

PS - you can actually just return self.items[-1] in peek(), no need to recalculate the size of the stack.

Upvotes: 1

Related Questions