From 6b9952c8a4d05ba4fb52c65e6726a6b0b336c171 Mon Sep 17 00:00:00 2001 From: Nourhan Alenany Date: Sun, 17 Jul 2022 22:41:22 -0700 Subject: [PATCH] Add solution to stacks and queues --- stacks_queues/queue.py | 31 +++++++++++++++++++++++++------ stacks_queues/stack.py | 19 ++++++++++++++----- 2 files changed, 39 insertions(+), 11 deletions(-) diff --git a/stacks_queues/queue.py b/stacks_queues/queue.py index d66dab2..208c900 100644 --- a/stacks_queues/queue.py +++ b/stacks_queues/queue.py @@ -23,34 +23,48 @@ def enqueue(self, element): In the store are occupied returns None """ - pass + if self.size == INITIAL_QUEUE_SIZE: + raise QueueFullException() + index = self.rear % self.buffer_size + self.store[index] = element + self.rear -= 1 + self.size += 1 def dequeue(self): """ Removes and returns an element from the Queue Raises a QueueEmptyException if The Queue is empty. """ - pass + if self.size == 0: + raise QueueEmptyException() + index = self.front % self.buffer_size + element = self.store[index] + self.front -= 1 + self.size -= 1 + return element def front(self): """ Returns an element from the front of the Queue and None if the Queue is empty. Does not remove anything. """ - pass + if self.size == 0: + return None + index = self.front % self.buffer_size + return self.store[index] def size(self): """ Returns the number of elements in The Queue """ - pass + return self.size def empty(self): """ Returns True if the Queue is empty And False otherwise. """ - pass + return self.size == 0 def __str__(self): """ Returns the Queue in String form like: @@ -58,4 +72,9 @@ def __str__(self): Starting with the front of the Queue and ending with the rear of the Queue. """ - pass + result = [] + for index in range(self.front, self.front - self.size, -1): + result.append(self.store[index % self.buffer_size]) + return str(result) + + diff --git a/stacks_queues/stack.py b/stacks_queues/stack.py index 94fb2a6..ec75756 100644 --- a/stacks_queues/stack.py +++ b/stacks_queues/stack.py @@ -12,22 +12,26 @@ def push(self, element): """ Adds an element to the top of the Stack. Returns None """ - pass + self.store.add_last(element) def pop(self): """ Removes an element from the top Of the Stack Raises a StackEmptyException if The Stack is empty. - returns None + returns the removed element """ - pass + if self.empty(): + raise StackEmptyException() + + return self.store.remove_last() + def empty(self): """ Returns True if the Stack is empty And False otherwise """ - pass + return self.store.empty() def __str__(self): """ Returns the Stack in String form like: @@ -35,4 +39,9 @@ def __str__(self): Starting with the top of the Stack and ending with the bottom of the Stack. """ - pass + values = [] + + current = self.store.get_last() + while current: + values.append(str(current.value)) + current = current.prev \ No newline at end of file