0
votes

I need to reverse a stack in python, my idea is to create an empty stack at the beginning. Then we test whether the original stack is empty, if it is so, then we have nothing to reverse; if not, every time we pop an item out of the original stack, we push it back to the empty stack. This continues until the original stack has nothing to pop out. And finally we rename the storage stack as the original stack, and return it. It should have a reverse order now.

But the problem is, for the unit test below, it never works, it turns out that the temp stack I get does not have a reverse order.

def test_reverse(self):

    stack = Stack()
    stack.push(1)
    stack.push(2)
    reverse(stack)
    self.assertEqual(stack.pop(), 1)
    self.assertEqual(stack.pop(), 2)
    self.assertTrue(stack.is_empty())

I really wonder why this does not work, thank you!

2
Have you seen the reversed() function? - Jonathon Reinhart
@MattBall, yes i understand, the top items in original stack goes to the bottom of temp stack, then when we pop out items from temp stack, we should get a reverse order. :( - rexarski
Won't you need to do stack = reverse(stack) instead of just reverse(stack)? - Pradeep Kumar
@PradeepKumar tried, doesn't work :( - rexarski
You also probably need to replace temp = temp.push(stuff) with temp.push(stuff) because you already have the temp stack. Not tested though. Just try. - Pradeep Kumar

2 Answers

1
votes

reverse(stack) is producing an answer, then throwing it out. Put it into a new variable; it's not reversing in place.

0
votes

If you are interested in using first in, first out (FIFO), you should probably be implementing a Queue as your data structure, not a Stack. Common implementations of Queues are also generally more flexible in application for what it seems you are trying to accomplish.