コード例 #1
0
def test_multipop_maxheap():
    maxheap = BinaryHeap([7, 9, 18, 1, 38, 5.4, 6, 200], minheap=False)
    length = len(maxheap)
    maxheap.pop()
    maxheap.pop()
    maxheap.push(400)
    maxheap.pop()
    maxheap.pop()
    assert maxheap.pop() == 9
    assert len(maxheap) == length - 4
コード例 #2
0
def test_multipop_minheap():
    minheap = BinaryHeap([7, 9, 18, 1, 38, 5.4, 6, 200])
    length = len(minheap)
    minheap.pop()
    minheap.pop()
    minheap.push(0)
    minheap.pop()
    minheap.pop()
    assert minheap.pop() == 7
    assert len(minheap) == length - 4
コード例 #3
0
 def test_binary_heap_pop(self):
     bh = BinaryHeap()
     bh.push(1)
     bh.push(3)
     bh.push(2)
     self.assertEqual(bh.pop(), 3)
     self.assertEqual(bh.size(), 2)
     self.assertEqual(bh.pop(), 2)
     self.assertEqual(bh.size(), 1)
     self.assertEqual(bh.pop(), 1)
     self.assertEqual(bh.size(), 0)
コード例 #4
0
def shorted_path(G, src):
    dist = {}
    pred = {}

    n = 0
    infinity = sys.maxint

    for v in G.keys():
        dist[v] = infinity
        pred[v] = None
        n +=1

    dist[src] = 0
    bh = BinaryHeap(n, src, infinity)

    while not bh.isEmpty():
        u = bh.pop()
        for v, w in G[u]:
            newLen = dist[u] + w
            if newLen < dist[v]:
                dist[v] = newLen
                bh.decreaseKey(v, newLen)
                pred[v] = u

    return dist, pred
コード例 #5
0
def test_pop():
    bt = BinaryHeap()
    for i in range(50):
        bt.push(random.randint(0,1000))

    for i in range(49):
        tmp = max(bt._list[1:])
        bt.pop()
        assert  tmp == bt._list[0]
    bt.pop()
    assert 0 == len(bt._list)

    # testing for empty list pop
    a = BinaryHeap()
    with pytest.raises(IndexError):
        assert a.pop()
コード例 #6
0
def test_pop_returns_sorted_values():
    """Test pop entire bin returns sorted values."""
    from binary_heap import BinaryHeap
    import random
    rand_nums = list(set([random.randint(0, 1000000000)
                          for i in range(10000)]))
    b = BinaryHeap(rand_nums)
    # import pdb; pdb.set_trace()
    all_popped = [b.pop() for i in range(1, len(b.heap))]
    assert all_popped == sorted(rand_nums, reverse=True)
コード例 #7
0
def test_binary_heap():
    _heap = BinaryHeap()

    with raises(IndexError):
        _heap.pop()

    _heap.push(2)
    _heap.push(20)
    _heap.push(-12)
    _heap.push(223)
    _heap.push(12)
    _heap.push(-2)
    sortedList = _heap.values

    assert _heap.values == [223, 20, -2, 2, 12, -12]

    _heap.pop()
    _heap.pop()

    assert _heap.values == [12, 2, -2, -12]
コード例 #8
0
def test_binary_heap():
    _heap = BinaryHeap()
    
    with raises(IndexError):
        _heap.pop()
    
    _heap.push(2)
    _heap.push(20)
    _heap.push(-12)
    _heap.push(223)
    _heap.push(12)
    _heap.push(-2)
    sortedList = _heap.values
    
    assert _heap.values == [223, 20, -2, 2, 12, -12]
    
    _heap.pop()
    _heap.pop()
    
    assert _heap.values == [12, 2, -2, -12]
コード例 #9
0
class PriorityQueue(object):
    def __init__(self):
        self.heap = BinaryHeap()
        self.seniority = 0

    def insert(self, priority, val):
        self.heap.push((priority, self.seniority, val))
        self.seniority -= 1

    def pop(self):
        try:
            return self.heap.pop()[2]
        except IndexError:
            raise IndexError("The queue is empty")

    def peek(self):
        try:
            return self.heap._list[0][2]
        except IndexError:
            raise IndexError("The queue is empty")
コード例 #10
0
def test_pop_maintains_heap():
    test_heap = B_heap(TEST_ARRAY_2)

    assert test_heap.pop() == 15
    assert test_heap._list == [14, 8, 12, 7, 6]
コード例 #11
0
def test_pop_empty():
    test_heap = B_heap()

    with pytest.raises(IndexError) as error:
        test_heap.pop()
    assert 'The heap is empty' in str(error.value)
コード例 #12
0
def test_pop_raises_index_error():
    """Popping from empty heap should raise an index error."""
    from binary_heap import BinaryHeap
    b = BinaryHeap()
    with pytest.raises(IndexError):
        b.pop()
コード例 #13
0
def test_pop_minheap():
    minheap = BinaryHeap([7, 9, 18, 1, 38, 5.4, 6])
    minheap.push(0)
    length = len(minheap)
    assert minheap.pop() == 0
    assert len(minheap) == length - 1
コード例 #14
0
def test_valid_instantiation_max(input, output):
    """Test instantiation by creating and doing one pop"""
    heap_under_test = BinaryHeap(input, minheap=False)
    assert is_maxheap_sorted(heap_under_test)
    assert heap_under_test.pop() == output
コード例 #15
0
class PriorityQ(object):
    """A class for a priority queue."""
    def __init__(self, iterable=()):
        """Initialize a priority queue, optionally with items from iterable.

        The items in the priority queue are stored in a binary minheap. Items
        are first sorted by priority, then queue insertion order. Priority is
        expressed as an integer with 0 being the most important.

        args:
            iterable: an optional iterable to add to the priority queue. Items
                      added this way will be given a priority of None.

        each item inside iterable can be either:
        * A QNode object
        * A container with value, priority
        * A non-iterable value

        """
        self.heap = BinaryHeap(iterable=())
        for item in iterable:
            try:
                is_container = len(item) == 2
            except TypeError:  # Case of QNode or non-iterable item
                self.insert(item)
            else:
                if is_container:  # Case of value, iterable
                    self.insert(item[0], item[1])
                else:
                    raise TypeError(
                        "More than two args: instantiation supports\
                                 non-iter value or iter of value, priority")

    def __repr__(self):
        return repr(self.heap)

    def __len__(self):
        return len(self.heap)

    def __iter__(self):
        return iter(self.heap)

    def __getitem__(self, index):
        return self.heap[index]

    def __setitem__(self, index, value):
        self.heap[index] = value

    def insert(self, item, priority=None):
        """Insert an item into the priority queue.

        If the item is a QNode object, it will be added tracking queue order.
        If not, a new QNode object is created to hold the item with queue order
        and optional priority assigned.

        args:
            item: the item to add (QNode or other value)
            priority: the optional integer priority (0 is most important)
        """
        if isinstance(item, QNode):
            item.order = len(self)
            self.heap.push(item)
        else:
            self.heap.push(QNode(item, priority=priority, order=len(self)))

    def pop(self):
        """Remove and return the most important item from the queue."""
        return self.heap.pop().val

    def peek(self):
        """Return the most important item from queue without removal."""
        return self.heap[0].val
コード例 #16
0
def test_pop_maintains_heap_2():
    test_heap = B_heap(TEST_ARRAY)

    assert test_heap.pop() == 646
    assert test_heap._list == [235, 123, 32, 3, 7]
コード例 #17
0
def test_pop_maxheap():
    maxheap = BinaryHeap([7, 9, 18, 1, 38, 5.4, 6], minheap=False)
    maxheap.push(400)
    length = len(maxheap)
    assert maxheap.pop() == 400
    assert len(maxheap) == length - 1
コード例 #18
0
class PriorityQ(object):
    """A class for a priority queue."""
    def __init__(self, iterable=()):
        """Initialize a priority queue, optionally with items from iterable.

        The items in the priority queue are stored in a binary minheap. Items
        are first sorted by priority, then queue insertion order. Priority is
        expressed as an integer with 0 being the most important.

        args:
            iterable: an optional iterable to add to the priority queue. Items
                      added this way will be given a priority of None.

        each item inside iterable can be either:
        * A QNode object
        * A container with value, priority
        * A non-iterable value

        """
        self.heap = BinaryHeap(iterable=())
        for item in iterable:
            try:
                is_container = len(item) == 2
            except TypeError:  # Case of QNode or non-iterable item
                self.insert(item)
            else:
                if is_container:  # Case of value, iterable
                    self.insert(item[0], item[1])
                else:
                    raise TypeError("More than two args: instantiation supports\
                                 non-iter value or iter of value, priority")

    def __repr__(self):
        return repr(self.heap)

    def __len__(self):
        return len(self.heap)

    def __iter__(self):
        return iter(self.heap)

    def __getitem__(self, index):
        return self.heap[index]

    def __setitem__(self, index, value):
        self.heap[index] = value

    def insert(self, item, priority=None):
        """Insert an item into the priority queue.

        If the item is a QNode object, it will be added tracking queue order.
        If not, a new QNode object is created to hold the item with queue order
        and optional priority assigned.

        args:
            item: the item to add (QNode or other value)
            priority: the optional integer priority (0 is most important)
        """
        if isinstance(item, QNode):
            item.order = len(self)
            self.heap.push(item)
        else:
            self.heap.push(QNode(item, priority=priority, order=len(self)))

    def pop(self):
        """Remove and return the most important item from the queue."""
        return self.heap.pop().val

    def peek(self):
        """Return the most important item from queue without removal."""
        return self.heap[0].val