def test_enqueue_dequeue(self): lq = LinkedQueue() element = "No-Flex Zone" lq.enqueue(element) dequeued_el = lq.dequeue() self.assertEqual(dequeued_el, element) self.assertEqual(lq.count, 0)
def test_to_array(self): lq = LinkedQueue() array = [0, 1, 2, 3, 4] for num in array: lq.enqueue(num) self.assertEqual(list(lq), array)
def breadthfirst(self): """Generate a breadth-first iteration of the positions of the tree.""" if not self.is_empty(): fringe = LinkedQueue() # known positions not yet yielded fringe.enqueue(self.root()) # starting with the root while not fringe.is_empty(): p = fringe.dequeue() # remove from front of the queue yield p # report this position for c in self.children(p): fringe.enqueue(c) # add children to back of the queue def inorder(self): """Generate an inorder iteration of positions in the tree.""" if not self.is_empty(): for p in self._subtree_inorder(self.root()): yield p def _subtree_inorder(self, p): """Generate an inorder iteration of positions in subtree rooted at p.""" if self.left(p) is not None: # if left child exists, traverse its subtree for other in self._subtree_inorder(self.left(p)): yield other yield p # visit p between its subtrees if self.right(p) is not None: # if right child exists, traverse its subtree for other in self._subtree_inorder(self.right(p)): yield other # Support for performing an inorder traversal of a binary tree. def positions(self): """Generate an iteration of the tree's positions.""" return self.inorder() # make inorder the default
def walk(self, num_sentences=10): # Get random starting point from keys starting_points = list(filter(lambda x: x[0] is None, self.keys())) chain = list(random.choice(starting_points)) queue = LinkedQueue(chain) sentences = 0 while sentences < num_sentences: prev_words = tuple(queue.items()) new_word = self[prev_words].sample() queue.enqueue(new_word) queue.dequeue() if new_word is None: sentences += 1 else: chain.append(new_word) phrase = [] for segment in chain[1:]: # Word if re.match(r'\w+', segment) is None: phrase[-1] += segment else: phrase.append(segment) result = ' '.join(phrase) return result
def LevelOrderTrav(tree): queue = LinkedQueue() queue.enqueue(tree) while not queue.is_empty(): to_print = queue.dequeue() print(to_print._element, end=' ') for i in children(to_print): queue.enqueue(i)
def breadthfirst(self): if not self.is_empty(): fringe = LinkedQueue() fringe.enqueue(self.root()) while not fringe.is_empty(): pos = fringe.dequeue() yield pos for child in self.children(pos): fringe.enqueue(child)
def breadthfirst(self): if not self.is_empty(): fringe = LinkedQueue() fringe.enqueue(self.root()) while not fringe.is_empty(): p = fringe.dequeue() yield p for c in self.children(p): fringe.enqueue(c)
def test_dequeue_order(self): lq = LinkedQueue() for num in range(5): lq.enqueue(num) self.assertEqual(lq.count, num + 1) for num in range(5): self.assertEqual(lq.count, 5 - num) dequeued_number = lq.dequeue() self.assertEqual(dequeued_number, num)
def breadthfirst(self): """Generate a breadth-first iteration of the nodes of the tree.""" if not self.is_empty(): fringe = LinkedQueue() # known nodes not yet yielded fringe.enqueue(self._root) # starting with the root while not fringe.is_empty(): node = fringe.dequeue() # remove from front of the queue yield node # report this node for c in self.children(node): fringe.enqueue(c) # add children to back of queue
def breadthfirst(self): """Generate a breadth-first iteration of the positions of the tree.""" if not self.is_empty(): fringe = LinkedQueue() # known positions not yet yielded fringe.enqueue(self.root()) # starting with the root while not fringe.is_empty(): p = fringe.dequeue() # remove from front of the queue yield p # report this position for c in self.children(p): fringe.enqueue(c) # add children to back of queue
def find_path_bfs(self, from_vert, to_vert): """ Return a list of vertex that represent a path from one vertex to another Runtime: O(V + E) """ if from_vert not in self.vertices_dict or to_vert not in self.vertices_dict: print('{} or {} are not in dictionary of vertices'.format( from_vert, to_vert)) return elif from_vert == to_vert: print('Both from vertex and to vertex are the same') return [self.vertices_dict[from_vert]] queue = LinkedQueue() queue.enqueue( (self.vertices_dict[from_vert], None)) # Enqueue the from vertex # A dictionary to keep track of the visited vertices along with their predecessor visited_dict = {self.vertices_dict[from_vert].data: None} while not queue.is_empty(): value = queue.dequeue() # curr_vertex = (Vertex, Parent Vertex) curr_vertex = value[0] if curr_vertex.data == to_vert: break for neighbor in curr_vertex.get_neighbors(): if neighbor not in visited_dict: # Enqueue the neighbor along with the current vertex as the parent vertex new_value = (self.vertices_dict[neighbor], curr_vertex) queue.enqueue(new_value) # Add the neighbor to the visited dictionary visited_dict[new_value[0].data] = new_value[1] # Cover case for disjointed graph if to_vert not in visited_dict: return path = [self.vertices_dict[to_vert]] next_vertex = visited_dict[to_vert] while next_vertex is not None: path.append(next_vertex) next_vertex = visited_dict[next_vertex.data] path.reverse() return path
def breadth_first(self): """ Generates a breadth first traversal of a Tree's positions """ if not self.is_empty(): q = LinkedQueue() q.enqueue(self.root()) while not q.is_empty(): for c in self.children(q.first()): q.enqueue(c) yield q.dequeue()
def levelorderPrint(self): """Generate a breadth-first iteration of the positions of the tree.""" if not self.is_empty(): queue = LinkedQueue() # known positions not yet yielded queue.enqueue(self.root()) # starting with the root while not queue.is_empty(): p = queue.dequeue() # remove from front of the queue # yield p # report this position print("from levelOrder: ", p.element()) for c in self.children(p): # add children to back of queue queue.enqueue(c)
def find_path_bfs(self, from_vert, to_vert): # Algorithm from Wikipedia and The Coding Train help understand it """ Return a list of vertex that represent a path from one vertex to another Runtime: O(V + E) """ if from_vert not in self.vertices_dict or to_vert not in self.vertices_dict: print('{} or {} are not in dictionary of vertices'.format(from_vert, to_vert)) return elif from_vert == to_vert: print('Both from vertex and to vertex are the same') return [self.vertices_dict[from_vert]] queue = LinkedQueue() queue.enqueue((self.vertices_dict[from_vert], 0)) # Enqueue the from vertex # A dictionary to keep track of the visited vertices along with their predecessor visited_dict = {self.vertices_dict[from_vert].id: None} while not queue.is_empty(): value = queue.dequeue() # curr_vertex = (Vertex, length) curr_vertex = value[0] if curr_vertex.id == to_vert: break for neighbor in curr_vertex.get_neighbors(): if neighbor not in visited_dict: # Enqueue the neighbor with an incremented length new_value = (self.vertices_dict[neighbor], curr_vertex) queue.enqueue(new_value) # Add the neighbor to the visited dictionary visited_dict[new_value[0].id] = new_value[1] # If unable to find the path if to_vert not in visited_dict: return path = [self.vertices_dict[to_vert]] next_vertex = visited_dict[to_vert] while next_vertex is not None: path.append(next_vertex) next_vertex = visited_dict[next_vertex.id] path.reverse() return path
def breadthfirst(self): """Generate a breadth-first iteration of the positions of the tree.""" # Add children to the queue when the "visits" learn of them, go back and actually visit # them later once they reach head of the queue. if not self.is_empty(): fringe = LinkedQueue( ) # Known postiions not yet yielded are placed in the queue fringe.enqueue(self.root()) while not fringe.is_empty(): p = fringe.dequeue() # remove from front of the queue yield p for c in self.children(p): fringe.enqueue(c) # add children to back of the queue
def breadthfirst(self): if not self.is_empty(): fringe = LinkedQueue() # start with root, push it to the back fringe.enqueue(self.root()) while not fringe.is_empty(): # remove from the front p = fringe.dequeue() yield p # push more from the back # it will remove from the top tier then go the lowest (leaf) for c in self.children(p): fringe.enqueue(c)
def quick_sort_queue(S): """Sort the elements of queue S using the quick-sort algorithm.""" n = len(S) if n < 2: return Lt = LinkedQueue() Eq = LinkedQueue() Gt = LinkedQueue() pivot = S.dequeue() Eq.enqueue(pivot) while not S.is_empty(): val = S.dequeue() if val < pivot: Lt.enqueue(val) elif val > pivot: Gt.enqueue(val) else: Eq.enqueue(val) quick_sort_queue(Lt) quick_sort_queue(Gt) while not Lt.is_empty(): S.enqueue(Lt.dequeue()) while not Eq.is_empty(): S.enqueue(Eq.dequeue()) while not Gt.is_empty(): S.enqueue(Gt.dequeue())
def merge_sort_queue(S): """Sort the elements of queue S using the merge-sort algorithm.""" n = len(S) if n < 2: return S1 = LinkedQueue() S2 = LinkedQueue() while len(S1) < n // 2: S1.enqueue(S.dequeue()) while not S.is_empty(): S2.enqueue(S.dequeue()) merge_sort_queue(S1) merge_sort_queue(S2) merge_queue(S1, S2, S)
def merge_sort(S): """Sort the elements of queue S using the merge-sort algorithm.""" n = len(S) if n < 2: return # list is already sorted # divide S1 = LinkedQueue() # or any other queue implementation S2 = LinkedQueue() while len(S1) < n // 2: # move the first n//2 elements to S1 S1.enqueue(S.dequeue()) while not S.is_empty(): # move the rest to S2 S2.enqueue(S.dequeue()) # conquer (with recursion) merge_sort(S1) # sort first half merge_sort(S2) # sort second half # merge results merge(S1, S2, S) # merge sorted halves back into S
def bfs(g,start): start.setDistance(0) start.setPred(None) vertQueue = LinkedQueue() print("enqueue:", start.getId()) vertQueue.enqueue(start) while (vertQueue.size() > 0): currentVert = vertQueue.dequeue() print(" dequeue:", currentVert.getId()) for nbr in currentVert.getConnections(): if (nbr.getColor() == 'white'): nbr.setColor('gray') nbr.setDistance(currentVert.getDistance() + 1) nbr.setPred(currentVert) vertQueue.enqueue(nbr) print("enqueue:", nbr.getId()) currentVert.setColor('black')
def main(): n = 100000 myQueue = LinkedQueue() start = time.clock() for count in range(n): myQueue.enqueue(count) end = time.clock() print("Time to enqueue", n, "items to a LinkedQueue was %.9f seconds" % (end - start)) start = time.clock() for count in range(n): temp = myQueue.dequeue() end = time.clock() print("Time to dequeue", n, "items to a LinkedQueue was %.9f seconds" % (end - start))
def breadth_first_search_length(self, vertex, length): """ Perform breadth first search and return all nodes that met the require length from the inputted vertex. Runtime: O(V + E) """ if vertex not in self.vertices_dict: return vertices = [] # Create queue to store nodes not yet traversed in level-order queue = LinkedQueue() # Enqueue given starting node and a length of 0 queue.enqueue((self.vertices_dict[vertex], 0)) # Queue = [(vertex, length), ... ] visited_dict = {self.vertices_dict[vertex].id: 0} # A dictionary to keep track of the visited vertices while not queue.is_empty(): value = queue.dequeue() # curr_vertex = (Vertex, length) curr_vertex = value[0] vertex_length = value[1] # Fast break if there current vertex's length is bigger than the target if vertex_length > length: break for neighbor in curr_vertex.get_neighbors(): if neighbor not in visited_dict: if vertex_length + 1 == length: # If the neighbor met the require length vertices.append(self.vertices_dict[neighbor]) # Enqueue the neighbor with an incremented length new_value = (self.vertices_dict[neighbor], vertex_length + 1) queue.enqueue(new_value) # Add the neighbor to the visited dictionary visited_dict[new_value[0].id] = new_value[1] return vertices
def BFS(g, s, discovered_list): """ :param g: Graph -- the graph :param s: Vertex -- the starting vertex for BFS :param discovered_list: List[Vertex] -- use this to mark discovered vertices Perform BFS of the undiscovered portion of Graph g starting at Vertex s. :return: Nothing, discovered_list will contain BFS order as you mark. """ # To do task 4 curr_level = LinkedQueue() next_level = LinkedQueue() curr_level.enqueue(s) discovered_list[s] = 'Marked' while curr_level.is_empty() == False: currNode = curr_level._head while currNode != None: Vertex = currNode._element #check every adjacent nodes with current Vertex for edge in g.incident_edges(Vertex): dst = edge.opposite(Vertex) #opposite vertex #check if dst already checked if discovered_list.get(dst) is not None: continue discovered_list[dst] = 'Marked' next_level.enqueue(dst) #enqueue newly discovered node currNode = currNode._next #second while loop quit, clearing curr_level queue while curr_level.is_empty() != True: curr_level.dequeue() #transferring all next_level vertex to curr_level while next_level.is_empty() != True: memo = next_level.dequeue() curr_level.enqueue(memo)
def quick_sort_queue(S): """sort elements of queue S using quick sort""" n = len(S) if n < 2: return # list is already sorted # divide pivot = S.first() # use first element as the pivot L = LinkedQueue() E = LinkedQueue() G = LinkedQueue() while not S.is_empty(): if S.first() < pivot: L.enqueue(S.dequeue()) elif pivot < S.first(): G.enqueue(S.dequeue()) else: # val is equal to pivot E.enqueue(S.dequeue()) # Conquer (with recursion) quick_sort_queue(L) # sorts elements less than pivot quick_sort_queue(G) # sorts elements greater than pivot # combine elements while not L.is_empty(): S.enqueue(L.dequeue()) while not E.is_empty(): S.enqueue(E.dequeue()) while not G.is_empty(): S.enqueue(G.dequeue())
def quick_sort(S): """Sort the elements of queue S using the quick-sort algorithm.""" n = len(S) if n < 2: return # list is already sorted # divide p = S.first() # using first as arbitrary pivot L = LinkedQueue() E = LinkedQueue() G = LinkedQueue() while not S.is_empty(): # divide S into L, E, and G if S.first() < p: L.enqueue(S.dequeue()) elif p < S.first(): G.enqueue(S.dequeue()) else: # S.first() must equal pivot E.enqueue(S.dequeue()) # conquer (with recursion) quick_sort(L) # sort elements less than p quick_sort(G) # sort elements greater than p # concatenate results while not L.is_empty(): S.enqueue(L.dequeue()) while not E.is_empty(): S.enqueue(E.dequeue()) while not G.is_empty(): S.enqueue(G.dequeue())
def quick_sort(S): n = len(S) if n >= 11: p = pick_pivot(S,0, n -1 ) L = LinkedQueue() E = LinkedQueue() G = LinkedQueue() while not S.is_empty(): initial = S.head.val if initial< p: L.enqueue(S.dequeue()) elif p < initial: G.enqueue(S.dequeue()) else: E.enqueue(S.dequeue()) quick_sort(L) quick_sort(G) while not L.is_empty(): S.enqueue(L.dequeue()) while not E.is_empty(): S.enqueue(E.dequeue()) while not G.is_empty(): S.enqueue(G.dequeue()) else: S.head = insertion_sort(S)
def quick_sort(t): l = len(t) if l < 2: return pivot = t.get_first() lt = LinkedQueue() gt = LinkedQueue() et = LinkedQueue() while not t.is_empty(): if t.get_first() < pivot: lt.enqueue(t.dequeue()) elif t.get_first() > pivot: gt.enqueue(t.dequeue()) else: et.enqueue(t.dequeue()) quick_sort(lt) quick_sort(gt) #order: less than, equal to, greater than~ while not lt.is_empty(): t.enqueue(lt.dequeue()) while not et.is_empty(): t.enqueue(et.dequeue()) while not gt.is_empty(): t.enqueue(gt.dequeue())
def levelorderPrint(self, node): queue = LinkedQueue() queue.enqueue(node) while not queue.is_empty(): next_node = queue.dequeue() print("From levelorderPrint:", next_node._element) if next_node._left: queue.enqueue(next_node._left) if next_node._right: queue.enqueue(next_node._right)
def levelOrderTraversal(tree): if tree == None: return queue = LinkedQueue() queue.enqueue(tree) while not queue.is_empty(): next_node = queue.dequeue() print(next_node._element, end=" ") if next_node._left: queue.enqueue(next_node._left) if next_node._right: queue.enqueue(next_node._right)
def levelorderPrint(self, node): """ :param node: TreeNode -- a given TreeNode. Prints all the elements with level order traversal, starting at the given node. :return: nothing. """ fringe = LinkedQueue() if node._parent != None: for i in self.children(node._parent): fringe.enqueue(i) else: fringe.enqueue(node) while not fringe.is_empty(): node = fringe.dequeue() print(node._element, end=' ') for i in self.children(node): fringe.enqueue(i)
L = LinkedQueue() E = LinkedQueue() G = LinkedQueue() while not S.is_empty(): # divide S into L, E, and G if S.first() < p: L.enqueue(S.dequeue()) elif p < S.first(): G.enqueue(S.dequeue()) else: # S.first() must equal pivot E.enqueue(S.dequeue()) # conquer (with recursion) quick_sort(L) # sort elements less than p quick_sort(G) # sort elements greater than p # concatenate results while not L.is_empty(): S.enqueue(L.dequeue()) while not E.is_empty(): S.enqueue(E.dequeue()) while not G.is_empty(): S.enqueue(G.dequeue()) lq = LinkedQueue() lq.enqueue(6) lq.enqueue(3) lq.enqueue(1) lq.enqueue(4) lq.enqueue(2) quick_sort(lq)