Ejercicio
Implementación De Una Cola Mediante Listas
Objectivo
Desarrollar un programa en Python para implementar una cola usando una lista. El programa debe incluir funcionalidad para poner en cola elementos, sacarlos de la cola y mostrar el estado actual de la cola. Garantizar un manejo adecuado de los errores en las operaciones en una cola vacía.
Ejemplo de ejercicio de Python
Mostrar código Python
class Queue:
"""Class to implement a queue using a list."""
def __init__(self):
"""Initializes the queue as an empty list."""
self.queue = []
def enqueue(self, item):
"""Adds an item to the end of the queue."""
self.queue.append(item)
print(f"Item '{item}' added to the queue.")
def dequeue(self):
"""Removes and returns the first item from the queue."""
if self.is_empty():
print("Error: The queue is empty. Cannot perform dequeue.")
else:
item = self.queue.pop(0)
print(f"Item '{item}' removed from the queue.")
return item
def is_empty(self):
"""Checks if the queue is empty."""
return len(self.queue) == 0
def display(self):
"""Displays the current state of the queue."""
if self.is_empty():
print("The queue is empty.")
else:
print("Current state of the queue:", self.queue)
def main():
"""Main function to interact with the queue."""
q = Queue()
while True:
print("\nOptions:")
print("1. Enqueue (Add item to the queue)")
print("2. Dequeue (Remove item from the queue)")
print("3. Display queue state")
print("4. Exit")
choice = input("Choose an option (1/2/3/4): ")
if choice == "1":
item = input("Enter the item to add to the queue: ")
q.enqueue(item)
elif choice == "2":
q.dequeue()
elif choice == "3":
q.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 state
4. Exit
Choose an option (1/2/3/4): 1
Enter the item to add to the queue: Apple
Item 'Apple' added to the queue.
Options:
1. Enqueue (Add item to the queue)
2. Dequeue (Remove item from the queue)
3. Display queue state
4. Exit
Choose an option (1/2/3/4): 3
Current state of the queue: ['Apple']
Options:
1. Enqueue (Add item to the queue)
2. Dequeue (Remove item from the queue)
3. Display queue state
4. Exit
Choose an option (1/2/3/4): 2
Item 'Apple' removed from the queue.
Options:
1. Enqueue (Add item to the queue)
2. Dequeue (Remove item from the queue)
3. Display queue state
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 state
4. Exit
Choose an option (1/2/3/4): 4
Exiting the program.
Código de ejemplo copiado
Comparte este ejercicio de Python