Ejercicio
Trabajar Con Colecciones De Colas
Objectivo
Desarrollar un programa Python para demostrar el uso de colecciones de colas. Utilizar el módulo de cola para implementar una cola básica con operaciones para agregar elementos, eliminar elementos y mostrar la cola. Asegurarse de que el programa maneje casos extremos, como intentar realizar operaciones en una cola vacía.
Ejemplo de ejercicio de Python
Mostrar código Python
import queue
class QueueDemo:
"""Class to demonstrate queue operations using the queue module."""
def __init__(self):
"""Initializes the queue."""
self.q = queue.Queue()
def enqueue(self, item):
"""Adds an item to the queue."""
self.q.put(item)
print(f"Item '{item}' added to the queue.")
def dequeue(self):
"""Removes and returns the item from the front of the queue."""
if self.is_empty():
print("Error: The queue is empty. Cannot perform dequeue.")
else:
item = self.q.get()
print(f"Item '{item}' removed from the queue.")
return item
def is_empty(self):
"""Checks if the queue is empty."""
return self.q.empty()
def display(self):
"""Displays the current contents of the queue."""
if self.is_empty():
print("The queue is empty.")
else:
# Convert the queue to a list for display purposes
print("Current contents of the queue:", list(self.q.queue))
def main():
"""Main function to interact with the queue."""
queue_demo = QueueDemo()
while True:
print("\nOptions:")
print("1. Enqueue (Add item to the queue)")
print("2. Dequeue (Remove item from the queue)")
print("3. Display queue contents")
print("4. Exit")
choice = input("Choose an option (1/2/3/4): ")
if choice == "1":
item = input("Enter the item to enqueue: ")
queue_demo.enqueue(item)
elif choice == "2":
queue_demo.dequeue()
elif choice == "3":
queue_demo.display()
elif choice == "4":
print("Exiting the program.")
break
else:
print("Invalid option. Please choose a valid option.")
# Run the program
if __name__ == "__main__":
main()
Output
Options:
1. Enqueue (Add item to the queue)
2. Dequeue (Remove item from the queue)
3. Display queue contents
4. Exit
Choose an option (1/2/3/4): 1
Enter the item to enqueue: Book
Item 'Book' added to the queue.
Options:
1. Enqueue (Add item to the queue)
2. Dequeue (Remove item from the queue)
3. Display queue contents
4. Exit
Choose an option (1/2/3/4): 3
Current contents of the queue: ['Book']
Options:
1. Enqueue (Add item to the queue)
2. Dequeue (Remove item from the queue)
3. Display queue contents
4. Exit
Choose an option (1/2/3/4): 2
Item 'Book' removed from the queue.
Options:
1. Enqueue (Add item to the queue)
2. Dequeue (Remove item from the queue)
3. Display queue contents
4. Exit
Choose an option (1/2/3/4): 3
The queue is empty.
Options:
1. Enqueue (Add item to the queue)
2. Dequeue (Remove item from the queue)
3. Display queue contents
4. Exit
Choose an option (1/2/3/4): 4
Exiting the program.
Código de ejemplo copiado
Comparte este ejercicio de Python