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()
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
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)
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)
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()
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
def test_pop(iterable, expected): from binheap import BinHeap bh = BinHeap(iterable) bh.pop() assert bh._container == expected
def test_pop_empty_heap(): from binheap import BinHeap bh = BinHeap() with pytest.raises(IndexError): bh.pop()
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
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()
def pop_empty(): heap = BinHeap() with pytest.raises(IndexError): heap.pop()
def test_pop_last(): heap = BinHeap() heap.push(5) assert heap.pop() == 5 assert heap.list == []
def test_pop_one_child(): heap = BinHeap() heap.push(5) heap.push(10) assert heap.pop() == 5