def __init__(self, items=None):
     """Initialize a priority queue and insert the given items, if any."""
     # Initialize new binary min heap to store items in this priority queue
     self.heap = BinaryMinHeap()
     if items:
         for item in items:
             self.heap.insert(item)
Exemple #2
0
def heap_sort(items):
    heap = BinaryMinHeap(items)

    sorted_items = []

    while heap.size() > 0:
        sorted_items.append(heap.delete_min())

    items[:] = sorted_items
class PriorityQueue(object):
    """PriorityQueue: a partially ordered queue with methods to enqueue items
    in priority order and to access and dequeue its highest priority item.
    Item pairs are stored in a binary min heap for its efficient operations."""

    def __init__(self):
        """Initialize this priority queue."""
        # Initialize new binary min heap to store items in this priority queue
        self.heap = BinaryMinHeap()

    def __repr__(self):
        """Return a string representation of this priority queue."""
        return 'PriorityQueue({} items, front={})'.format(self.size, self.front())

    def size(self):
        """returns the number of items in the queue"""
        return self.heap.size()

    def is_empty(self):
        """Return True if this priority queue is empty, or False otherwise."""
        return self.heap.is_empty()

    def length(self):
        """Return the number of items in this priority queue."""
        return self.heap.size()

    def enqueue(self, item, priority=0):
        """Insert the given item into this priority queue in order according to
        the given priority."""
        # Insert given item into heap in order according to given priority
        self.heap.insert((priority, item))

    def front(self):
        """Return the item at the front of this priority queue without removing
        it, or None if this priority queue is empty."""
        if self.size() == 0:
            return None
        # Return minimum item from heap
        return self.heap.get_min()[1]

    def dequeue(self):
        """Remove and return the item at the front of this priority queue,
        or raise ValueError if this priority queue is empty."""
        if self.size() == 0:
            raise ValueError('Priority queue is empty and has no front item')
        # Remove and return minimum item from heap
        return self.heap.delete_min()[1]

    def push_pop(self, item, priority):
        """Remove and return the item at the front of this priority queue,
        and insert the given item in order according to the given priority.
        This method is more efficient than calling dequeue and then enqueue."""
        if self.size() == 0:
            raise ValueError('Priority queue is empty and has no front item')
        # Replace and return minimum item from heap
        self.heap.items[0], popped_item = (priority, item), self.heap.items[0]
        self.heap._bubble_down(0)
        return popped_item[1]
Exemple #4
0
 def test_insert_and_get_one_item(self):
     heap = BinaryMinHeap()
     assert heap.is_empty() is True
     heap.insert(5)
     assert heap.is_empty() is False
     assert heap.size() == 1
     assert heap.get_min() == 5
     assert heap.items == [5]
Exemple #5
0
class PriorityQueue(object):
    """ PriorityQueue: a partially ordered queue with methods to enqueue items
    in priority order and to access and dequeue its highest priority item.\n
    Item pairs are stored in a binary min heap for its efficient operations. """
    def __init__(self):
        """ Initializes priority queue. """
        self.heap = BinaryMinHeap(
        )  # Initializes new binary min heap to store items in priority queue

    def __repr__(self):
        """ Returns string representation of priority queue. """
        return "PriorityQueue({} items, front={})".format(
            self.size(), self.front())

    def is_empty(self):
        """ Returns True if priority queue is empty, else returns False. """
        return self.heap.is_empty()

    def length(self):
        """ Returns number of items in priority queue. """
        return self.heap.size()

    def enqueue(self, item, priority):
        """ Inserts given item into priority queue in order according to given priority. """
        # TODO: Inserts given item into heap in order according to given priority

    def front(self):
        """ Returns item at front of priority queue without removing
        it, or None if priority queue is empty. """
        if self.size() == 0:
            return None
        # TODO: Returns minimum item from heap
        # ...

    def dequeue(self):
        """ Removes and returns item at front of priority queue,
        or raises ValueError if priority queue is empty. """
        if self.size() == 0:
            raise ValueError("Priority queue is empty and has no front item.")
        # TODO: Removes and returns minimum item from heap
        # ...

    def push_pop(self, item, priority):
        """ Removes and returns item at front of priority queue,
        and inserts given item in order according to given priority.\n
        This method is more efficient than calling dequeue and then enqueue."""
        if self.size() == 0:
            raise ValueError("Priority queue is empty and has no front item.")
 def test_heapify_on_small_array(self):
     '''Compare the output of heapify to creating a BinaryMinHeap.'''
     items = [6, 8, 3, 5, 7, 3]
     heap = BinaryMinHeap(items)
     items = heapify(items)
     for i, j in zip(items, heap.items):
         assert i == j
Exemple #7
0
 def test_insert_and_get_many_items(self):
     heap = BinaryMinHeap()
     items = [9, 25, 86, 3, 29, 5, 55]
     for index, item in enumerate(items):
         heap.insert(item)
         assert heap.size() == index + 1
         min_item = min(items[: index + 1])
         assert heap.get_min() == min_item
     assert heap.size() == len(items)
     assert heap.items == [3, 9, 5, 25, 29, 86, 55]
     assert heap.is_empty() is False
 def test_insert_and_delete_many_items(self):
     heap = BinaryMinHeap()
     items = [9, 25, 86, 3, 29, 5, 55]
     for item in items:
         heap.insert(item)
     assert heap.size() == len(items)
     for item in sorted(items):
         assert heap.delete_min() == item
     assert heap.size() == 0
 def test_insert_and_get_many_random_items(self):
     heap = BinaryMinHeap()
     items = random.sample(range(1000), 50)
     for index, item in enumerate(items):
         heap.insert(item)
         assert heap.size() == index + 1
         min_item = min(items[:index + 1])
         assert heap.get_min() == min_item
     assert heap.size() == len(items)
 def test_insert_and_delete_many_random_items(self):
     heap = BinaryMinHeap()
     items = random.sample(range(1000), 50)
     for item in items:
         heap.insert(item)
     assert heap.size() == len(items)
     for item in sorted(items):
         assert heap.delete_min() == item
     assert heap.size() == 0
def get_suggestion(org_handle, handle_array, k=2) -> [str]:
    assert len(handle_array) >= k

    suggestion_min_heap = BinaryMinHeap()

    handle_set = set(org_handle)  # O(c)

    for handle in handle_array:  # O(n)
        if suggestion_min_heap.size() < k:
            curr_score = get_score(handle_set, handle)  # O(c)
            suggestion_min_heap.insert((handle, curr_score))  # O(k)

        elif suggestion_min_heap.get_min()[1] > len(
                handle):  # Check whether to get the score or not
            continue

        else:
            curr_score = get_score(handle_set, handle)  # O(c)
            if curr_score > suggestion_min_heap.get_min()[1]:
                suggestion_min_heap.replace_min((handle, curr_score))

    return [x[0] for x in suggestion_min_heap.items]  # O(k)
class PriorityQueue:
    def __init__(self):
        self._heap = BinaryMinHeap()
        self._max_priority = 0
        self._min_priority = 0

    def _update_minmax(self, priority):
        if priority > self._max_priority:
            self._max_priority = priority
        if priority < self._min_priority:
            self._min_priority = priority

    @property
    def size(self):
        return self._heap.size

    @property
    def front(self):
        if self.is_empty() is False:
            return self._heap.get_min().value
        else:
            return None

    def dequeue(self):
        return self._heap.delete_min().value

    def enqueue(self, item):
        self.insert_back(item)

    def push_pop(self, item):
        self.insert_back(item)
        return self._heap.delete_min().value

    def is_empty(self):
        return self._heap.is_empty()

    def insert(self, item, priority):
        self._heap.insert(KVHolder(priority, item))
        self._update_minmax(priority)

    def insert_front(self, item):
        priority = self._min_priority - 1
        self.insert(item, priority)

    def insert_back(self, item):
        priority = self._max_priority + 1
        self.insert(item, priority)
 def test_child_index(self):
     heap = BinaryMinHeap()
     assert heap._left_child_index(0) == 1
     assert heap._right_child_index(0) == 2
     assert heap._left_child_index(1) == 3
     assert heap._right_child_index(1) == 4
     assert heap._left_child_index(2) == 5
     assert heap._right_child_index(2) == 6
     assert heap._left_child_index(3) == 7
     assert heap._right_child_index(3) == 8
     assert heap._left_child_index(4) == 9
     assert heap._right_child_index(4) == 10
     assert heap._left_child_index(5) == 11
     assert heap._right_child_index(5) == 12
     assert heap._left_child_index(6) == 13
     assert heap._right_child_index(6) == 14
 def test_insert_and_delete_one_item(self):
     heap = BinaryMinHeap()
     heap.insert(5)
     assert heap.size() == 1
     assert heap.delete_min() == 5
     assert heap.size() == 0
 def test_heapify(self):
     items = random.sample(range(1000), 6)
     heap = BinaryMinHeap(items)
     assert self.has_heap_order(heap.items) is True
     items = [0, 3, 6, 4, 5, 8, 9]
     assert self.has_heap_order(items)
 def test_insert_and_get_one_item(self):
     heap = BinaryMinHeap()
     heap.insert(5)
     assert heap.size() == 1
     assert heap.get_min() == 5
     assert heap.items == [5]
Description:
    Binary Heap: a simple example test example
"""

from test_utilities import compare_var, compare_arr_similar, summarize_results
from binaryheap import BinaryMinHeap

GLOBAL_PRINT_DEBUG = False


if __name__ == "__main__":
    runtime = []
    results = []
    print "####################################################"
    print("Test Case 1")
    bheap = BinaryMinHeap()
    results.append(compare_var(bheap.is_empty(), True, "=="))
    results.append(compare_var(bheap.peek_min(), None, "=="))
    results.append(compare_var(bheap.remove_min(), None, "=="))
    results.append(compare_var(bheap.peek_array(), [], "=="))

    print "####################################################"
    print("Test Case 2")
    val = 5
    print("\nAdd one value to the heap: {0}".format(val))
    bheap.insert(val)
    results.append(compare_var(bheap.is_empty(), False, "=="))
    results.append(compare_var(bheap.peek_min(), val, "=="))
    results.append(compare_var(bheap.peek_array(), [5], "=="))

    print "####################################################"
 def __init__(self):
     self._heap = BinaryMinHeap()
     self._max_priority = 0
     self._min_priority = 0
 def test_delete_min_on_empty_heap(self):
     heap = BinaryMinHeap()
     with self.assertRaises(ValueError):
         heap.delete_min()
 def __init__(self):
     """Initialize this priority queue."""
     # Initialize new binary min heap to store items in this priority queue
     self.heap = BinaryMinHeap()
 def test_size_of_empty_heap(self):
     heap = BinaryMinHeap()
     assert heap.size() == 0
Exemple #22
0
class PriorityQueue(object):
    """PriorityQueue: a partially ordered queue with methods to enqueue items
    in priority order and to access and dequeue its highest priority item.
    Item pairs are stored in a binary min heap for its efficient operations."""

    def __init__(self):
        """Initialize this priority queue."""
        # Initialize new binary min heap to store items in this priority queue
        self.heap = BinaryMinHeap()

    def __repr__(self):
        """Return a string representation of this priority queue."""
        return 'PriorityQueue({} items, front={})'.format(self.size(), self.front())

    def is_empty(self):
        """Return True if this priority queue is empty, or False otherwise."""
        return self.heap.is_empty()

    def length(self):
        """Return the number of items in this priority queue."""
        return self.heap.size()

    def enqueue(self, item, priority):
        """Insert the given item into this priority queue in order according to
        the given priority."""
        # TODO: Insert given item into heap in order according to given priority
        # ...
        # Note that I probably could have done this with a list instead
        self.heap.insert((priority, item))

    def front(self):
        """Return the item at the front of this priority queue without removing
        it, or None if this priority queue is empty."""
        if self.size() == 0: # Basically, if the queue is empty, then just retirn that theres no front
            return None

        # TODO: Return minimum item from heap
        # ...
        front_item =  self.heap.get_min()
        return front_item[1]

    def dequeue(self):
        """Remove and return the item at the front of this priority queue,
        or raise ValueError if this priority queue is empty."""
        if self.size() == 0:
            raise ValueError('Priority queue is empty and has no front item')
        # TODO: Remove and return minimum item from heap
        # ...
        last_item = self.heap.delete_min()
        return last_item[1]

    def push_pop(self, item, priority):
        """Remove and return the item at the front of this priority queue,
        and insert the given item in order according to the given priority.
        This method is more efficient than calling dequeue and then enqueue."""
        if self.size() == 0:
            raise ValueError('Priority queue is empty and has no front item')
        # TODO: Replace and return minimum item from heap
        # ...
        popped_item = self.heap.replace_min(priority, item)
        return popped_item[1]
Exemple #23
0
 def __init__(self):
     """ Initializes priority queue. """
     self.heap = BinaryMinHeap(
     )  # Initializes new binary min heap to store items in priority queue
class PriorityQueue(object):
    """
    PriorityQueue: a partially ordered queue with methods to enqueue items
    in priority order and to access and dequeue its highest priority item.
    Item pairs are stored in a binary min heap for its efficient operations.
    """
    def __init__(self):
        """Initialize this priority queue."""
        # Initialize new binary min heap to store items in this priority queue
        self.heap = BinaryMinHeap()

    def __repr__(self):
        """Return a string representation of this priority queue."""
        return 'PriorityQueue({} items, front={})'.format(
            self.length(), self.front())

    # def __str__(self):
    #     pass

    def is_empty(self):
        """Return True if this priority queue is empty, or False otherwise."""
        return self.heap.is_empty()

    def length(self):
        """Return the number of items in this priority queue."""
        return self.heap.size()

    def enqueue(self, item, priority):
        """
        Insert the given item into this priority queue in order according to
        the given priority.
        """
        # Insert given item into heap in order according to given priority
        new_item = (item, priority)
        self.heap.insert(new_item)

    def front(self):
        """
        Return the item at the front of this priority queue without removing
        it, or None if this priority queue is empty.
        """
        if self.length() == 0:
            return None
        return self.heap.get_min()[0]

    def dequeue(self):
        """
        Remove and return the item at the front of this priority queue,
        or raise ValueError if this priority queue is empty.
        """
        if self.length() == 0:
            raise ValueError('Priority queue is empty and has no front item')
        # delete the min element
        front_elem = self.heap.delete_min()

        return front_elem[0]

    def push_pop(self, item, priority):
        """
        Remove and return the item at the front of this priority queue,
        and insert the given item in order according to the given priority.
        This method is more efficient than calling dequeue and then enqueue.
        """
        if self.length() == 0:
            raise ValueError('Priority queue is empty and has no front item')
        # store the old front item
        old_front = self.front()

        # replace the item at the 0th element with new item and its priority
        self.heap.items[0] = (item, priority)
        # print(f"new front item: {self.front()}")
        return old_front[0]
 def test_parent_index(self):
     heap = BinaryMinHeap()
     with self.assertRaises(IndexError):
         heap._parent_index(0)
     assert heap._parent_index(1) == 0
     assert heap._parent_index(2) == 0
     assert heap._parent_index(3) == 1
     assert heap._parent_index(4) == 1
     assert heap._parent_index(5) == 2
     assert heap._parent_index(6) == 2
     assert heap._parent_index(7) == 3
     assert heap._parent_index(8) == 3
     assert heap._parent_index(9) == 4
     assert heap._parent_index(10) == 4
     assert heap._parent_index(11) == 5
     assert heap._parent_index(12) == 5
     assert heap._parent_index(13) == 6
     assert heap._parent_index(14) == 6
 def test_is_empty_on_empty_heap(self):
     heap = BinaryMinHeap()
     assert heap.is_empty() == True
Exemple #27
0
def heap_sort(items):
    heap = BinaryMinHeap(items)
    for index, mass in enumerate(heap):
        items[index] = mass
    return items
 def test_is_empty_on_non_empty_heap(self):
     heap = BinaryMinHeap()
     heap.insert(1)
     assert heap.is_empty() == False