Imagine a queue is like a line at your favorite amusement park ride. People join the line (enqueue) at the back and exit (dequeue) from the front. Here is the catch: you can't just jump ahead of everyone else! The first person who joined the line gets on the ride first. Just like that, a queue follows the "First In, First Out" (FIFO) rule. So, in essence, a queue is like a well-behaved line of people, patiently waiting for their turn, ensuring fairness and order in processing tasks or data.
Come and join me in implementing a queue using Python.
Note: To avoid conflicts with Queue
class in the Python standard library, we define a custom MyQueue
class.
from typing import Any, Optional
class MyQueue:
def __init__(self) -> None:
self.items: list = []
def is_empty(self) -> bool:
return len(self.items) == 0
def size(self) -> int:
return len(self.items)
def enqueue(self, item: Any) -> None:
self.items.insert(0, item)
def dequeue(self) -> Optional[Any]:
if not self.is_empty():
return self.items.pop()
else:
return None
Message queue is the most intuitive application of queue. Now use MyQueue
to implement a simple message queue.
from my_queue import MyQueue
from typing import Any, Optional
class MessageQueue:
def __init__(self):
self.queue = MyQueue()
def send_message(self, message: Any) -> None:
self.queue.enqueue(message)
print("Message sent:", message)
def receive_message(self) -> Optional[Any]:
if not self.queue.is_empty():
return self.queue.dequeue()
else:
return None
def main() -> None:
mq = MessageQueue()
mq.send_message("hello, world")
mq.send_message("this is python")
mq.send_message("ketechy")
print("---------------")
print(mq.receive_message())
print(mq.receive_message())
if __name__ == "__main__":
main()
'''
Output:
Message sent: hello, world
Message sent: this is python
Message sent: ketechy
---------------
hello, world
this is python
ketechy
None
'''