예제 #1
0
class Queue:
    def __init__(self):
        self._data_stack = Stack()
        self._utility_stack = Stack()

# Complexity: 2 * O(n)?? for 2 for loops, but not nested!

    def enqueue(self, item):
        if self._data_stack.__len__() < 1:
            self._data_stack.push(item)
            return
        for _ in range(
                self._data_stack.__len__()
        ):  # "_" instead of an i variable means you don't care about the variable (saves memory)
            popped_item = self._data_stack.pop()
            self._utility_stack.push(popped_item)
        self._data_stack.push(item)
        for _ in range(self._utility_stack.__len__()):
            self._data_stack.push(self._utility_stack.pop())
            #everything is on the data stack in the original order

# Complexity: O(1)

    def dequeue(self):
        if self._data_stack.__len__() < 1:
            raise Exception("queue is empty")
        return self._data_stack.pop()


# pop removes the data item that's been there the longest, when in a queue

    def __len__(self):
        return len(self._data_stack)
예제 #2
0
    def test_push_len(self):

        #Arrange
        my_stack = Stack()
        my_stack.push(1)
        my_stack.push(2)
        my_stack.push(3)

        #Act
        length = my_stack.__len__()

        #Assert
        self.assertEqual(3, length, "len did not return correct length")