0

I tried to implement a queue using 2 stacks using the code below.

Utility Stack implementation.

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

    def is_empty(self):
        return self.array == []

    def pop(self):
        if self.array == []:
            raise Exception('stack is empty')
        else:
            popped_element = self.array.pop()
            return popped_element

    def push(self,key):
        self.array.append(key)

    def top(self):
        return self.array[-1]

    def __repr__(self):
        return " ".join(list(map(str,self.array)))



if __name__ == "__main__":
    q = Stack()
    q.push(1)
    q.push(2)
    q.push(3)
    q.push(4)
    q.push(5)
    print(q.pop())
    print(q.pop())
    print(q.pop())
    q.push(10)
    print(q)
from stack import Stack
class TwoStackQueue1():
    def __init__(self):
        self.stack1 = Stack()
        self.stack2 = Stack()

    def enqueue(self,key):
        self.stack1.push(key)

    def dequeue(self):
        while(self.stack1.is_empty() != True):
            top = self.stack1.top()
            print("eval_dequeue",top)
            self.stack2.push(top)
            self.stack1.pop()


        if self.stack2.is_empty() == True:
            raise Exception("Queue is empty")
        else:
            top = self.stack2.pop()
            return top

    def is_empty():
        return self.stack1.is_empty() and self.stack2.is_empty()

if __name__ == "__main__":
    q = TwoStackQueue1()
    q.enqueue(1)
    q.enqueue(2)
    q.enqueue(3)
    q.enqueue(4)
    q.enqueue(5)
    print(q.stack1)
    print(q.dequeue())

when i tried to perform above operations on the queue , my code is getting stuck in infinite recursion because pop operation of my stack is not working . Can someone please help me figure out why my code (Queue operations:- q.dequeue()) is getting stuck in infinite recursion? Thanks.

  • 1
    Does this answer your question? ["Least Astonishment" and the Mutable Default Argument](https://stackoverflow.com/questions/1132941/least-astonishment-and-the-mutable-default-argument) – Klaus D. Mar 15 '20 at 04:19
  • 1
    And please allow me the comment that your Stack is nothing more than a reimplementation of some functions lists (they are not called arrays) already have. – Klaus D. Mar 15 '20 at 04:25
  • @KlausD.Thanks for the link , it solved my problem. I'm totally aware of the fact that the Stack class is nothing more than append and pop functions of the list. I created the class because I wanted to have an abstraction similar to stacks in other languages. – Pushya Mitra Mar 15 '20 at 04:48

1 Answers1

0

The problem is that you have effectively made the inner state of your object a Singleton, by virtue of the fact that you used a mutable default argument.

In other words, since the array you can initialize your Stack with is the empty list by default, any future instance will not just use an empty list, but will use the same list as all previous Stack instances.

Try this quick fix:

class Stack():
    def __init__(self,array=None):
        self.array = array or []
    ...
kojiro
  • 74,557
  • 19
  • 143
  • 201