Introduction:
Queues play a pivotal role in managing data structures. This tutorial delves into the implementation of queues in Python, covering key operations like enqueue and dequeue. Through real-world examples, you’ll learn how to create, manipulate, and efficiently manage queues, enhancing your Python programming skills along the way.
Code:
def isEmpty(myQueue):
return len(myQueue) == 0
def enqueue(myQueue, element):
myQueue.append(element)
def dequeue(myQueue):
if isEmpty(myQueue):
print('Queue is empty')
return None
else:
return myQueue.pop(0)
def size(myQueue):
return len(myQueue)
# Initialize the queue
myQueue = list()
# each person to be assigned a code as P1, P2, P3,...
element = input("Enter person’s code to enter in the queue: ")
enqueue(myQueue, element)
element = input("Enter person’s code for insertion in the queue: ")
enqueue(myQueue, element)
print("Person removed from the queue is:", dequeue(myQueue))
print("Number of people in the queue is:", size(myQueue))
element = input("Enter person’s code to enter in the queue: ")
enqueue(myQueue, element)
element = input("Enter person’s code to enter in the queue: ")
enqueue(myQueue, element)
element = input("Enter person’s code to enter in the queue: ")
enqueue(myQueue, element)
print("Now we are going to remove remaining people from the queue")
while not isEmpty(myQueue):
print("Person removed from the queue is", dequeue(myQueue))
print("queue is empty")
Logic:
- Define the isEmpty function to check if a queue is empty.
- Define the enqueue function to add an element to the queue.
- Define the dequeue function to remove and return the front element from the queue.
- Define the size function to calculate the number of elements in the queue.
- Initialize an empty myQueue list.
- Use the enqueue function to add elements (person’s codes) to the queue.
- Use the dequeue function to remove a person from the front of the queue and print their code.
- Use the size function to display the number of people in the queue.
- Continue adding elements to the queue.
- Use a loop to remove remaining people from the queue using the dequeue function.
Output:
>>Enter person’s code to enter in the queue: P1
>>Enter person’s code for insertion in the queue: P2
>>Person removed from the queue is: P1
>>Number of people in the queue is: 1
>>Enter person’s code to enter in the queue: P3
>>Enter person’s code to enter in the queue: P4
>>Enter person’s code to enter in the queue: P5
>>Now we are going to remove remaining people from the queue
>>Person removed from the queue is P2
>>Person removed from the queue is P3
>>Person removed from the queue is P4
>>Person removed from the queue is P5
>>queue is empty