Skip to content

File Name: basics_queue.py

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
print("""
Queue Class:
The basic FIFO queue. It is often used for thread-safe communication between threads in a multithreaded environment.
Example: from queue import Queue
""")

from queue import Queue

class CustomQueue:
  def __init__(self):
    self.queue = Queue()

  def enqueue(self, item):
    """Add an item to the end of the queue."""
    self.queue.put(item)

  def dequeue(self):
    """Remove and return the first item from the queue."""
    if not self.is_empty():
      return self.queue.get()
    else:
      print("Queue is empty")
      return None

  def is_empty(self):
    """Check if the queue is empty."""
    return self.queue.empty()

  def size(self):
    """Return the number of items in the queue."""
    return self.queue.qsize()

  def peek(self):
    """Return the first item in the queue without removing it."""
    if not self.is_empty():
      return self.queue.queue[0]
    else:
      print("Queue is empty")
      return None

# Example usage:
if __name__ == "__main__":
  grocery_queue = CustomQueue()
  print("Initial queue:", list(grocery_queue.queue.queue))

  # Adding people to the queue
  grocery_queue.enqueue("Venkat")
  grocery_queue.enqueue("Suba")
  grocery_queue.enqueue("Gutti")
  print("Queue after adding people:", list(grocery_queue.queue.queue))

  # Serving people from the queue
  serving_person = grocery_queue.dequeue()
  print("Serving:", serving_person)
  print("Queue after serving:", list(grocery_queue.queue.queue))

  # Checking the next person to be served
  next_person = grocery_queue.peek()
  print("Next person to be served:", next_person)

Documentation

from queue import Queue

class CustomQueue: def init(self): self.queue = Queue()

def enqueue(self, item): self.queue.put(item)

def dequeue(self): if not self.is_empty(): return self.queue.get() else: print("Queue is empty") return None

def is_empty(self): return self.queue.empty()

def size(self): return self.queue.qsize()

def peek(self): if not self.is_empty(): return self.queue.queue[0] else: print("Queue is empty") return None

Example usage:

if name == "main": grocery_queue = CustomQueue() print("Initial queue:", list(grocery_queue.queue.queue))

# Adding people to the queue grocery_queue.enqueue("Venkat") grocery_queue.enqueue("Suba") grocery_queue.enqueue("Gutti") print("Queue after adding people:", list(grocery_queue.queue.queue))

# Serving people from the queue serving_person = grocery_queue.dequeue() print("Serving:", serving_person) print("Queue after serving:", list(grocery_queue.queue.queue))

# Checking the next person to be served next_person = grocery_queue.peek() print("Next person to be served:", next_person)