Exemple #1
0
def instance_and_seq(request):
    """Return tuple of new BinHeap object and sequence that constructed it."""
    from binheap import BinHeap
    seq = request.param
    if seq is None:
        instance = BinHeap()
        seq = []
    else:
        instance = BinHeap(seq)

    return (instance, seq)
def random_heap():
    """Generate a list for use in a heap."""
    from binheap import BinHeap
    iterable = list(
        set([random.randint(0, 200) for _ in range(random.randrange(500))]))
    min_heap = BinHeap(iterable)
    return min_heap
Exemple #3
0
def test_binheap_constructed_with_iterable_is_filled_properly(itr):
    """Test that new binheap constructed with an iterable is filled."""
    from binheap import BinHeap
    h = BinHeap(itr)
    assert h._values[0] is None
    assert h._values[1] is itr[-1]
    assert h._size == len(itr)
Exemple #4
0
def test_push():
    from binheap import BinHeap
    sample_list = [16, 14, 15, 9, 7, 6, 5, 1, 2, 3]
    bh = BinHeap(sample_list)
    sample_list.append(4)
    bh.push(4)
    assert bh._container == sample_list
Exemple #5
0
def test_pop_from_random_min_heap_in_sorted_order():
    """Test that popping all the items from a heap are in sorted order."""
    from binheap import BinHeap
    from random import randint
    random_nums = [randint(0, 100) for _ in range(20)]
    h = BinHeap(random_nums, is_max_heap=False)
    popped = [h.pop() for _ in range(len(h._values) - 1)]
    assert popped == sorted(random_nums)
Exemple #6
0
def test_pop_from_unique_random_max_heap_in_sorted_order():
    """Test that popping all items from a unique heap are in sorted order."""
    from binheap import BinHeap
    from random import randint
    random_nums = list(set([randint(0, 100) for _ in range(20)]))
    h = BinHeap(random_nums)
    popped = [h.pop() for _ in range(len(h._values) - 1)]
    assert popped == sorted(random_nums, reverse=True)
Exemple #7
0
def main():

    # greeting
    print("Welcome to Alice's Restaurant")
    print("Open everyday except Thanksgiving.")

    # display command list
    print('Enter "a" to add a guest to the waiting list.')
    print(
        'Enter "s" to remove the next guest from the waiting list once they have been seated.'
    )
    print('Enter "q" to quit.')

    # initialize reservation list & guest tracking number
    reservationList = BinHeap()
    guestnumber = 0

    # get user imput
    command = input("Command: ")
    while command.lower() != "q":

        # add guest
        if command.lower() == "a":
            name = input("Guest name: ")
            priority = input("Guest priority: ")
            guestnumber += 1
            newguest = Guest(name, priority, guestnumber)
            reservationList.insert(newguest)
            print("A reservation for", newguest.name, "has been made.")
            print("They have been assigned a priority of",
                  newguest.priority + ".")
            print("They are currently", reservationList._heap.index(newguest),
                  "in line for a table.")
            command = input("Command: ")

        # get next guest from list
        elif command.lower() == "s":
            serving = reservationList.pop()

            # check if there are guests on list
            if serving:
                print("Now serving", serving.name)
                command = input("Command: ")

            # warn if no guests on list
            else:
                print("There are no customers on the waiting list")
                command = input("Command: ")

        # control for invalid commands
        elif command.lower() != "a" or "s":
            print("Unrecognised command! Please try again.")
            command = input("Command: ")

    # exit program
    else:
        print("Goodbye!")
        exit()
def heapSort(alist):
    """堆排序 O(nlogn)"""
    heap = BinHeap(len(alist))
    heap.buildHeap(alist)
    sort = []

    for i in range(len(alist), 0, -1):
        sort.append(heap.delMin())

    return sort
def heap_sort(my_list):
    sortlst = []  # create a list for sorted values
    heap = BinHeap()  # create a heap
    heap.buildHeap(my_list)  # build heap from an unsorted list
    while not heap.isEmpty():  # stop the loop when heap is empty
        sortlst.append(
            heap.delMin()
        )  # keep deleting the min value in the heap and reorganizing the heap and append the min value to sortlst

    return sortlst  # return the sorted list
Exemple #10
0
def heapSort(myList):
    # Create an empty heap
    minHeap = BinHeap()

    # Add all list items to minHeap
    minHeap.buildHeap(myList)

    # delMin heap items back to list in sorted order
    size = len(myList)
    for index in range(0, size):
        myList[index] = (minHeap.delMin())
Exemple #11
0
def dijkstra(vertice_list,src,num_ver):
  import CPUtimer

  timer = CPUtimer.CPUTimer()
  timer.reset()
  cond = False
  parent = []
  #marca todos os vertices como nao visitados
  for i in range(num_ver):
    parent.append(-1)
  #vertice inicial tem distancia 0.  Na 1 iteracao todos os demais estao setados com 'infinidade'
  vertice_list[src].dist=0

  from binheap import BinHeap
  f = BinHeap()
  f.insert(vertice_list[src].dist,src)
  #print("Nodes:",f.total_nodes)
  #pelo numero de vertices, escolha o vertice de menor distancia atualmente no grafo.
  #Na primeira iteracao sera o source. 
  i = 0
  while(f.currentSize!=0):
  #while(i<10):
    i+=1
    
    v_min_node = f.delMin() # 1.1
    #print('key:',v_min_node.key)
    #print("Nodes:",f.total_nodes)
    v_min = vertice_list[v_min_node[1]] 

    if(v_min==None):
      continue
    v_min.visited=1#marque vertice minimo como ja visitado. Desse modo o 1.2 sera feito, pois nao sera mais contado
    #para cada vertice adjacente ao vertice minimo
    for key in v_min.adjs:# 1.3
      adj_ver = vertice_list[v_min.adjs[key].id]#pega o vertice adjacente 
      #Se a distancia atual do vertice minimo, mais o seu peso, for menor que a distancia do vert adjacente
      if(adj_ver.visited==0 and  v_min.dist + v_min.weights[key] < adj_ver.dist ):
        adj_ver.dist = v_min.dist + v_min.weights[key] #a distancia do vertice adjacente tera esse novo valor
        parent[adj_ver.id] = v_min.id # a pos que era do vertice adjacente, sera do menor v agora
        f.insert(adj_ver.dist,adj_ver.id)
Exemple #12
0
def test_init_from_iter(iterable, expected):
    from binheap import BinHeap
    bh = BinHeap(iterable)
    assert bh._container == expected
Exemple #13
0
def test_init():
    from binheap import BinHeap
    bh = BinHeap()
    assert bh._container == []
Exemple #14
0
def test_pop(iterable, expected):
    from binheap import BinHeap
    bh = BinHeap(iterable)
    bh.pop()
    assert bh._container == expected
Exemple #15
0
def test_pop_empty_heap():
    from binheap import BinHeap
    bh = BinHeap()
    with pytest.raises(IndexError):
        bh.pop()
Exemple #16
0
def test_binheap_constructed_with_empty_iterable_is_empty():
    """Test that new binheap constructed with an empty iterable is empty."""
    from binheap import BinHeap
    h = BinHeap([])
    assert h._values[0] is None
    assert h._size == 0
Exemple #17
0
def test_binheap_constructed_with_invalid_iterable_raises_error(itr):
    """Test that new binheap constructed invalid iterable raises TypeError."""
    from binheap import BinHeap
    with pytest.raises(TypeError):
        BinHeap(itr)
Exemple #18
0
def test_find_right_child_of_random_node_in_binheap(idx, result):
    """Test that _rci returns the right child of selected index."""
    from binheap import BinHeap
    h = BinHeap()
    assert h._rci(idx) == result
Exemple #19
0
 def __init__(self):
     """Construct a new priority queue."""
     self._values = BinHeap()
     self._min_priority = 0
Exemple #20
0
 def __init__(self):
     self._heap = BinHeap()
def empty_heap():
    """Instantiate a heap for testing."""
    from binheap import BinHeap
    min_heap = BinHeap()
    return min_heap
Exemple #22
0
 def __init__(self):
     self._heap = BinHeap(order='min')
     self._cumulative_idx = 0
Exemple #23
0
def empty_min_binheap():
    """Create an empty minbinheap."""
    from binheap import BinHeap
    return BinHeap(is_max_heap=False)
Exemple #24
0
def empty_max_binheap():
    """Create an empty maxbinheap."""
    from binheap import BinHeap
    return BinHeap()
def sample_heap():
    """A fixture for a sample heap to use."""
    from binheap import BinHeap
    return BinHeap()
def full_heap():
    """Instantiate a heap from a list for testing."""
    from binheap import BinHeap
    min_heap = BinHeap([67, 5, 32, 1, 0, 2, 4, 101, 94, 72])
    return min_heap
Exemple #27
0
def test_find_parent_of_random_node_in_binheap(idx, result):
    """Test that _pi returns the parent of selected index."""
    from binheap import BinHeap
    h = BinHeap()
    assert h._pi(idx) == result
 def __init__(self, maxNode):
     self.priorityQueue = BinHeap(maxNode)
     self.dataDict = dict()
def test_heap_type_error():
    """Ensure TypeError if we pass anything but a list or None."""
    from binheap import BinHeap
    with pytest.raises(TypeError):
        test_heap = BinHeap(1, 2, 3, 4)