From 635869fc3e88f74e88ed281662039f7f1e7fe0ff Mon Sep 17 00:00:00 2001 From: Lereena Date: Sun, 30 Sep 2018 21:56:06 +0300 Subject: [PATCH 1/3] Add array realisation of queue on python --- Python/data-structures/queue_array.py | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 Python/data-structures/queue_array.py diff --git a/Python/data-structures/queue_array.py b/Python/data-structures/queue_array.py new file mode 100644 index 0000000..f0de705 --- /dev/null +++ b/Python/data-structures/queue_array.py @@ -0,0 +1,18 @@ +class Queue: + def __init__(self): + self.items = [] + + def enqueue(self, item): + self.items.insert(0, item) + + def dequeue(self): + return self.items.pop() + + def peek(self): + return self.items[0] + + def size(self): + return len(self.items) + + def is_empty(self): + return self.items == [] From 8fd50527ec8ebf09d0ee08742b6902cd183667bc Mon Sep 17 00:00:00 2001 From: Lereena Date: Sun, 30 Sep 2018 23:02:39 +0300 Subject: [PATCH 2/3] Correct python implementation of queue --- Python/data-structures/{queue_array.py => Queue.py} | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) rename Python/data-structures/{queue_array.py => Queue.py} (64%) diff --git a/Python/data-structures/queue_array.py b/Python/data-structures/Queue.py similarity index 64% rename from Python/data-structures/queue_array.py rename to Python/data-structures/Queue.py index f0de705..374a872 100644 --- a/Python/data-structures/queue_array.py +++ b/Python/data-structures/Queue.py @@ -6,10 +6,13 @@ def enqueue(self, item): self.items.insert(0, item) def dequeue(self): - return self.items.pop() + if self.is_empty(): + raise Exception("Queue is empty") + else: + return self.items.pop() def peek(self): - return self.items[0] + return self.items[-1] def size(self): return len(self.items) From 1dcd0e125c13dcbdf2fe9b473d21b560fd721ab7 Mon Sep 17 00:00:00 2001 From: Lereena Date: Sun, 30 Sep 2018 23:03:15 +0300 Subject: [PATCH 3/3] Add examples of using queue --- Python/data-structures/examples.py | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 Python/data-structures/examples.py diff --git a/Python/data-structures/examples.py b/Python/data-structures/examples.py new file mode 100644 index 0000000..6f15a6d --- /dev/null +++ b/Python/data-structures/examples.py @@ -0,0 +1,24 @@ +from Queue import Queue + +# ----------------- Queue ----------------- +q1 = Queue() + +# put elements in queue +q1.enqueue(42) +q1.enqueue(256) +q1.enqueue(6) + +# look at the top of the queue +print("Top element: ", q1.peek()) + +# use the top element +top = q1.dequeue() +print("Top element in variable: ", top) +print("Top element after using past top element: ", q1.peek()) + +print("Size of queue: ", q1.size()) +# we can just dequeue elements without using +q1.dequeue() +q1.dequeue() +print("Is queue empty now: ", q1.is_empty()) +