Beispiel #1
0
def merge_k(lists):
    # If lists is empty
    if not len(lists):
        return

    # Initializing an array containing the first element of each list
    data = [lst for lst in lists]

    # Initializing a heap with the data
    heap = Heap(data)

    # Extracting min and storing reference to the head
    result = heap.poll()
    head = result

    if result.next:
        heap.insert(result.next)

    # Extracting min and replacing with next one from list
    while not heap.is_empty():
        min_item = heap.poll()
        result.next = min_item
        result = result.next

        if min_item.next:
            heap.insert(min_item.next)

    return head
Beispiel #2
0
def test_insert():
    from heaps.heap import Heap
    heap = Heap()

    for i in range(10):
        heap.insert(i)

    assert len(heap.array) == 10
def test_insert():
    heap = Heap([])
    heap.insert(4)
    heap.insert(3)
    heap.insert(6)
    heap.insert(1)
    heap.insert(2)
    heap.insert(0)
    heap.insert(5)

    assert_values(heap)
    assert list(heap) == []
Beispiel #4
0
def test_delete():
    from random import shuffle
    from heaps.heap import Heap
    MAX_DATA = 100000

    heap = Heap()

    data = [x for x in range(MAX_DATA)]
    shuffle(data)
    for datum in data:
        heap.insert(datum)

    result = []
    for _ in range(MAX_DATA):
        result.append(heap.delete())

    data.sort(reverse=True)

    assert result == data