Пример #1
0
class PriorityQueue:
    def __init__(self):
        self._list = DoublyLinkedList()

    def __len__(self) -> int:
        return len(self._list)

    def __iter__(self) -> Generator[T]:
        yield from self._list

    def enqueue(self, data: T) -> None:
        if len(self) == 0:
            self._list.add_last(data)
        else:
            current = self._list.head

            while current and current.data > data:
                current = current.next_

            if current is None:
                self._list.add_last(data)
            else:
                self._list.add_before(current, data)

    def peek(self) -> T:
        if len(self) == 0:
            raise IndexError("peek from empty priority queue")
        return self._list.head.data

    def dequeue(self) -> T:
        if len(self) == 0:
            raise IndexError("dequeue from empty priority queue")
        data = self.peek()
        self._list.remove_first()
        return data
Пример #2
0
def test_container():
    linked_list = DoublyLinkedList()
    linked_list.add_last(1)
    linked_list.add_last(2)

    assert 1 in linked_list
    assert 2 in linked_list
    assert 3 not in linked_list
Пример #3
0
def test_reversed():
    linked_list = DoublyLinkedList()
    linked_list.add_last(1)
    linked_list.add_last(2)
    linked_list.add_last(3)

    values_list = [item for item in reversed(linked_list)]

    assert values_list == [3, 2, 1]
Пример #4
0
def test_iteration():
    linked_list = DoublyLinkedList()
    linked_list.add_last(1)
    linked_list.add_last(2)
    linked_list.add_last(3)

    values_list = [item for item in linked_list]

    assert values_list == [1, 2, 3]
Пример #5
0
def test_remove_added_last(method_name, size, head, tail):
    dll = DoublyLinkedList()

    for n in range(size):
        dll.add_last(n)

    method = getattr(dll, method_name)
    method()

    assert len(dll) == (size - 1)
    assert dll.head == head
    assert dll.tail == tail
Пример #6
0
def test_add_before_tail():
    linked_list = DoublyLinkedList()
    linked_list.add_last(1)
    linked_list.add_last(3)

    linked_list.add_before(linked_list.tail, 2)

    head = linked_list.head
    middle = head.next_
    tail = linked_list.tail

    assert head == 1
    assert head.previous is None
    assert head.next_ == middle

    assert middle == 2
    assert middle.previous == head
    assert middle.next_ == tail

    assert tail == 3
    assert tail.previous == middle
    assert tail.next_ is None