Reverse the order of words in python using stack

I am trying to use stack to reverse the order like if j="this is sentence" so the output will be "sentence is this" to do this I try to put it in stack and then pop them out like

stack.push(j.split(' '))    

and then pop it as

while not stack.is_empty()
  print stack.data.pop(),

but what stack.push(j.split(' ')) does it puts the whole sentence as single entity in the stack like

[['this','is','a','sentence']]

and hence when i pop it it gives result

['this','is','a','sentence']

means nothing reversed at all in nutshell.so how should i split and push the word in stack so that i can reverse the order of words.

Upvotes: 1

Views: 714

Answers (3)

AllwinP
AllwinP

Reputation: 71

stack.push(*j.split(' '))

Python does not consider the list returned by split as a list of arguments unless you explicitly specify that using an asterisk. Otherwise it will simply push a list on the stack

Upvotes: 0

Sk Borhan Uddin
Sk Borhan Uddin

Reputation: 813

First of all stack.push(j.split(' ')) doesnt return splited words. It returns an object with splited words. So that when you push j.split(' ') in a stack, it actually push all words as an object. In the end when you poped up it returns the last entry and that is the object ['this','is','a','sentence'].

class Stack():

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

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

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

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

  def getElements(self):
    return self.items

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

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

j="this is sentence"
stack = Stack()
jj = j.split(' ')
for word in jj:
    stack.push(word)
print stack.getElements()
print stack.peek() # shows you latest (last) value of array
print stack.pop()

In the code you'll find the object is traversed and pushed each word into stack. Then just simply pop each word.

Upvotes: 1

Irshad Bhat
Irshad Bhat

Reputation: 8709

stack.push places the given element/argument on top of stack. For you case the element/argument is whole list. You need to push each element of list seperately. So, replace:

stack.push(j.split(' '))

by:

for i in j.split():
    stack.push(i)

Upvotes: 2

Related Questions