예제 #1
0
class PriorityQ(object):
    """Class for implementing a priority queue."""
    def __init__(self):
        self._heap = BinHeap(order='min')
        self._cumulative_idx = 0

    def insert(self, pri, val):
        """Insert a value at the end of the priority queue."""
        self._heap.push((pri, self._cumulative_idx, val))
        self._cumulative_idx += 1

    def pop(self):
        """Remove and return the value at the root of the priority queue."""
        try:
            result = self._heap.pop()
            return result[2]
        except IndexError:
            raise IndexError("Cannot pop from empty queue.")

    def peek(self):
        """Return the value of at the root of the priority queue."""
        try:
            return self._heap._heap_list[0][2]
        except IndexError:
            return None
예제 #2
0
class PriorityQ(object):
    """Class for implementing a priority queue."""

    def __init__(self):
        self._heap = BinHeap(order='min')
        self._cumulative_idx = 0

    def insert(self, pri, val):
        """Insert a value at the end of the priority queue."""
        self._heap.push((pri, self._cumulative_idx, val))
        self._cumulative_idx += 1

    def pop(self):
        """Remove and return the value at the root of the priority queue."""
        try:
            result = self._heap.pop()
            return result[2]
        except IndexError:
            raise IndexError("Cannot pop from empty queue.")

    def peek(self):
        """Return the value of at the root of the priority queue."""
        try:
            return self._heap._heap_list[0][2]
        except IndexError:
            return None
예제 #3
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
예제 #4
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)
예제 #5
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)
예제 #6
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()
예제 #7
0
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
예제 #8
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)
예제 #9
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())
class PriorityQueue():
    """优先级队列"""
    def __init__(self, maxNode):
        self.priorityQueue = BinHeap(maxNode)
        self.dataDict = dict()

    def enqueue(self, priority, data):
        """入队"""
        self.priorityQueue.insert(priority)
        self.dataDict[priority] = data

    def dequeue(self):
        """出队"""
        pri = self.priorityQueue.delMin()
        return self.dataDict[pri]
예제 #11
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)
예제 #12
0
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
예제 #13
0
class Priorityq(object):
    def __init__(self):
        self.binheap = BinHeap()
        self._count = 0

    def insert(self, priority, val):
        new_node = Node(priority, val, self._count)
        self.binheap.push(new_node)
        self._count += 1

    def pop(self):
        return_node = self.binheap.pop()
        return return_node.val

    def peek(self):
        return self.binheap[0].val
예제 #14
0
class PriorityQueue:
    def __init__(self):
        self._heap = BinHeap()

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

    def enqueue(self, item):
        self._heap.insert(item)

    def dequeue(self):
        return self._heap.delMin()

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

    def __str__(self):
        return str(self._heap)
예제 #15
0
def full_heap():
    heap = BinHeap()
    heap.push(5)
    heap.push(4)
    heap.push(10)
    heap.push(7)
    heap.push(2)
    return heap
예제 #16
0
def find_split(segments):
    """Finds an appropriate pair of segments that differ enough in timbre but
    also don't lie two near the beginning or the end."""

    #initiate minimum binary heap instance
    deltas = BinHeap()

    #compares delta for each pair of segments (1,2), (2,3), etc... and save the values in deltas
    for i in range(len(segments)-2):
        deltas.insert((find_delta_segment(segments[i], segments[i+1]), i))

    #take the largest difference
    a = deltas.delMin()
    #makes sure that a is not too near the beginning (before 1/6 of song) or
    #the end (after 5/6 of song)
    while a[1] < len(segments)//4 or a[1] > (3*len(segments))//4:
        a = deltas.delMin()

    return a
예제 #17
0
def test_pull(full_heap, empty_heap):
    full_heap.pop()
    assert len(full_heap) == 11
    assert helper(full_heap) is True
    full_heap.pop()
    assert len(full_heap) == 10
    assert helper(full_heap) is True
    empty_heap = BinHeap()
    with pytest.raises(LookupError):
        empty_heap.pop()
    empty_heap.push(2)
    assert empty_heap.pop() == 2
    with pytest.raises(LookupError):
        empty_heap.pop()
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
예제 #19
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)
예제 #20
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)
예제 #21
0
def test_pop_last():
    heap = BinHeap()
    heap.push(5)
    assert heap.pop() == 5
    assert heap.list == []
예제 #22
0
 def __init__(self):
     self._heap = BinHeap(order='min')
     self._cumulative_idx = 0
예제 #23
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
예제 #24
0
def empty_max_binheap():
    """Create an empty maxbinheap."""
    from binheap import BinHeap
    return BinHeap()
예제 #25
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
예제 #26
0
def test_init():
    from binheap import BinHeap
    bh = BinHeap()
    assert bh._container == []
예제 #27
0
def test_pop_one_child():
    heap = BinHeap()
    heap.push(5)
    heap.push(10)
    assert heap.pop() == 5
예제 #28
0
파일: astar.py 프로젝트: csharrison/ASTAR
def create_path(s, end, grid,timelimit):
    "Creates the shortest path between s (start) and end."
    runtime = 0
    
    # yay nested list comprehension
    # the ons list is a 2d list of node status
    # None means the node has not been checked yet
    # a node object for a value means it is on the open list
    # a False value means that it is on the closed list
    ons = [[None for y in xrange(len(grid[x]))] for x in xrange(len(grid))]

    #n is the current best node on the open list, starting with the initial node
    n = node(s, None ,0, 0)

    #we store the fscores of the nodes and the nodes themselves in a binary heap
    openl = BinHeap()

    #local functions accessed faster than global functions
    get_time = time.clock
    geth = get_h_score
    while n.loc != end:
        t = get_time()

        #search adjacent nodes
        #if the node is already on the open list, then
        #and change their pointer the the current node
        #if their path from current node is shorter than their
        #previous path from previous parent
        #if the node is not on the open list and is not a wall,
        #add it to the open list
        for x in xrange(n.loc[0] -1, n.loc[0] +2):
            for y in xrange(n.loc[1] -1 , n.loc[1] + 2):
                #the checked node can't be our central node
                if (x,y) != n.loc:
                        
                    #if the node is not on the closed list or open list
                    if ons[x][y] != None and ons[x][y] != False:
                        #get cost of the new path made from switching parents
                        new_cost = getdircost(n.loc,(x,y)) + n.gscore

                        # if the path from the current node is shorter
                        if new_cost < ons[x][y].gscore:
                            #find the index of the node
                            #to change in the open list
                            index = openl.index([ons[x][y].fscore,ons[x][y]])

                            #update the node to include this new change
                            openl[index][1] = node((x,y), n, new_cost,
                                                   geth((x,y),end) + new_cost)
                            
                            #update the ons list and the fscore list in the heap
                            openl[index][0] = openl[index][1].fscore
                            ons[x][y] = openl[index][1]

                    #if the node is not a wall and not on the closed list
                    #then simply add it to the open list
                    elif grid[x][y] == True and ons[x][y] != False:
                        h = geth((x,y),end)
                        
                        #movement score gets the direction cost
                        #added to the parent's directional cost
                        g = getdircost(n.loc,(x,y)) + n.gscore

                        ons[x][y] = node((x, y), n, g, g+h)#turn it on baby
                        openl.add([g+h, ons[x][y]])




        #if the length of the open list is zero(all nodes on closed list)
        #then return an empty path list
        if len(openl) == 0:
            print runtime
            return []

        #pop from the binary heap (the zeroth index stores fscore only)
        #this will give the node with the smallest fscore, hopefully closer
        #to the goal
        n = openl.pop()[1]

        #remove from the 'closed' list
        ons[n.loc[0]][n.loc[1]] = False

        runtime += get_time()-t
        if runtime > timelimit:
            print runtime
            break


    #Now we have our path, we just need to trace it
    #trace the parent of every node until the beginning is reached
    moves = []
    while n.loc != s:
        moves.insert(0,n.loc)
        n = n.parent
    print runtime
    return moves 
예제 #29
0
 def __init__(self):
     """Construct a new priority queue."""
     self._values = BinHeap()
     self._min_priority = 0
예제 #30
0
def sample_heap():
    """A fixture for a sample heap to use."""
    from binheap import BinHeap
    return BinHeap()
예제 #31
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
예제 #32
0
def test_pop_empty_heap():
    from binheap import BinHeap
    bh = BinHeap()
    with pytest.raises(IndexError):
        bh.pop()
예제 #33
0
def test_push():
    heap = BinHeap()
    heap.push(5)
    assert heap.list[0] == 5
예제 #34
0
def test_pop(iterable, expected):
    from binheap import BinHeap
    bh = BinHeap(iterable)
    bh.pop()
    assert bh._container == expected
예제 #35
0
 def __init__(self):
     self.binheap = BinHeap()
     self._count = 0
예제 #36
0
def test_init_from_iter(iterable, expected):
    from binheap import BinHeap
    bh = BinHeap(iterable)
    assert bh._container == expected
예제 #37
0
def pop_empty():
    heap = BinHeap()
    with pytest.raises(IndexError):
        heap.pop()
예제 #38
0
def test_push_more():
    heap = BinHeap()
    heap.push(5)
    heap.push(4)
    assert heap.list[0] == 4
    assert heap.list[1] == 5
예제 #39
0
def empty_min_binheap():
    """Create an empty minbinheap."""
    from binheap import BinHeap
    return BinHeap(is_max_heap=False)
예제 #40
0
 def __init__(self):
     self._heap = BinHeap(order='min')
     self._cumulative_idx = 0
예제 #41
0
 def __init__(self):
     self._heap = BinHeap()
 def __init__(self, maxNode):
     self.priorityQueue = BinHeap(maxNode)
     self.dataDict = dict()
예제 #43
0
class PriorityQ(object):
    """Structure for values in a priorty queue.

    Items added to the priority queue are given a priority. If not set
    by the user, priority is set to be the lowest. When removing items,
    higher priority items are removed before lower priority items.
    """
    def __init__(self):
        """Construct a new priority queue."""
        self._values = BinHeap()
        self._min_priority = 0

    def __len__(self):
        """Overwrite length to give us the amount of items in priority Q.

        Get all the items from all the buckets in the priority Q.
        """
        return sum(len(b) for b in self._all_values[1:])

    @property
    def _all_values(self):
        return self._values._values

    @property
    def _size(self):
        return self._values._size

    def insert(self, val, priority=None):
        """Add a new value into the priority queue.

        If no priority is given, uses current lowest priority.
        """
        if priority is None:
            priority = self._min_priority

        if priority < self._min_priority:
            self._min_priority = priority

        try:
            i = self._all_values.index(priority)
            bucket = self._all_values[i]
            bucket._values.enqueue(val)

        except ValueError:
            self._values.push(Bucket(priority, [val]))

    def pop(self):
        """Remove the first value from priority Q.

        If no values in bucket then bucket is removed.
        """
        if len(self._all_values) < 2:
            raise IndexError('Can not pop from empty priority Q.')
        bucket = self._all_values[1]
        result = bucket._values.dequeue()
        if len(bucket._values) == 0:
            self._values.pop()
        return result

    def peek(self):
        """Get the the most important item without removing it."""
        if len(self._all_values) < 2:
            return
        bucket = self._all_values[1]
        return bucket._values.peek()