Aún no tienes acceso a esta clase

Crea una cuenta y continúa viendo este curso

Queue basada en listas

19/23
Recursos

Aportes 5

Preguntas 2

Ordenar por:

¿Quieres ver más aportes, preguntas y respuestas de la comunidad? Crea una cuenta o inicia sesión.

Para obtener el tamaño, simplemente aplicaría la función len() a la lista self.items.

self.size = len(self.items)

El código de la clase


class ListQueue:
    def __init__(self):
        self.items = []
        self.size = 0
    
    def enqueue(self,data):
        self.items.insert(0,data)
        self.size += 1

    def dequeue(self):
        data = self.items.pop()
        self.size -= 1
        return data
    
    def traverse(self):
        total_items = self.size

        for item in range(total_items):
            print(self.items[item])

from list_based_queue import ListQueue

food = ListQueue()
food.enqueue('eggs')
food.enqueue('ham')
food.enqueue('spam')
print(food.dequeue())
food.traverse()
eggs
spam
ham 

Opinion:
Me confunde un poco el que inserte un nuevo valor en el índice 0, ya que contradice un poco el funcionamiento de las listas. Considerando que en el índice 0 está el primer elemento de la lista, creo que quedaría mejor utilizar append() y pop(0).

Queue con list implementando métodos básicos

from typing import List
from typing import Any
from typing import Iterable
from typing import Optional
from node import Node


class Queue:
    """Represents a simple queue."""

    _items: List

    def __init__(self, *items) -> None:
        """Initializes the Queue"""
        self._items = []

        if len(items) > 0 and isinstance(items[0], Iterable):
            items = items[0]

        for item in items:
            self.enqueue(item)

    def clear(self):
        """Clears the queue.

        Time complexity: O(1)
        """

        self._items = []

    def peek(self):
        """Returns the first element of the queue.

        Raises IndexError if the queue is empty.

        Time complexity: O(1)

        Returns:
            Any: First element of the queue.
        """

        if len(self._items) == 0:
            raise IndexError('The queue is empty.')

        return self._items[0]

    def is_empty(self) -> bool:
        """Check if the queue is empty.

        Returns:
            bool: True if the queue is empty. False otherwise.
        """

        return len(self._items) == 0

    def enqueue(self, value: Any) -> None:
        """Adds a new value to the queue.

        Time Complexity: O(n)

        Args:
            value (Any): Value to be added.

        Returns:
            None
        """

        self._items.append(value)

        return None

    def dequeue(self):
        """Removes a value from the queue.

        Raises IndexError if the queue is empty.

        Time complexity: O(n)

        Returns:
            Any: Removed value.
        """

        if len(self._items) == 0:
            raise IndexError('The queue is empty.')

        value = self._items.pop(0)

        return value

    def copy(self):
        """Returns a copy of the current queue.

        Time complexity: O(1)

        Returns:
            Queue: Copy of the current queue.
        """

        new_queue = Queue()

        new_queue._items = self._items

        return new_queue

    def depthcopy(self):
        """Returns a copy of the current queue.

        This function will create a copy of value in the queue.

        Time Complexity: O(n)

        Returns:
            Queue: Copy of the queue.
        """

        new_queue = Queue()

        new_queue._items = [item for item in self]

        return new_queue

    def itervalues(self) -> Iterable[Any]:
        """Generates an iterable of the values in the queue.

        Time complexity: O(n)

        Returns:
            Iterable: Iterable of the values in the queue.
        """

        return iter(self._items)

    def __len__(self) -> int:
        """Returns the length of the queue when using the `len` built-in function.

        Time complexity: O(1)

        Returns:
            int: Number of nodes into the queue.
        """

        return len(self._items)

    def __str__(self):
        """Returns a string representation of the queue.

        Time complexity: O(n)

        Args:
            str: Representation of the queue
        """

        return '->'.join(self._items)

    def __iter__(self) -> Iterable[Any]:
        """Generates an iterable of the values in the queue.

        Time complexity: O(n)

        Returns:
            Iterable: Iterable of the values in the queue.
        """

        return self.itervalues()

    def __contains__(self, value: Any) -> bool:
        """Checks if a value is in the queue.

        Time complexity: O(n)

        Args:
            value: Value to be searched in the queue.

        Returns:
            bool: True if the value is in the queue. False otherwise.
        """

        for item in self:
            if item == value:
                return True

        return False

    def __add__(self, other: Iterable) -> 'Queue':
        """Returns a new queue with the items of both queues.

        Time complexity: O(n)

        Args:
            other (Iterable): Items to be added to the current queue.

        Returns:
            Queue: New queue with the items of both queues.
        """

        new_queue = self.depthcopy()

        new_queue._items += [item for item in other]

        return new_queue

wooo estupendo