Ejemplo n.º 1
0
 def add(self, newItem):
     '''inserts new item after items of greater or equal priority or ahead of items of lesser priority. 
     A has greater priority than B if A < B
     Assumes newItem is a comparable (see Comparable class)
     '''
     print('hey')
     if self.isEmpty() or newItem >= self.rear.data:
         # new item goes to rear, use super class method and pass self into first argument position
         LinkedQueue.add(self, newItem)
     else:
         # search for position where the new item is less
         probe = self.front
         # step through nodes until newItem is less than or equal to probe.data
         while newItem >= probe.data:
             trailer = probe
             probe = probe.next
         # instantiate new Node for new item to go into the queue
         newNode = Node(newItem, probe)
         if probe == self.front:
             # new item goes to front
             self.front = newNode
         else:
             # new item goes between two nodes
             trailer.next = newNode
         self.size += 1
 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 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)
Ejemplo n.º 5
0
 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)
Ejemplo n.º 6
0
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 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
Ejemplo n.º 8
0
 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 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)
Ejemplo n.º 10
0
 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 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
Ejemplo n.º 12
0
 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
Ejemplo n.º 13
0
    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
Ejemplo n.º 14
0
    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
Ejemplo n.º 15
0
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))
Ejemplo n.º 16
0
 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 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)
Ejemplo n.º 18
0
    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
Ejemplo n.º 19
0
 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)
Ejemplo n.º 20
0
 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
Ejemplo n.º 21
0
 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
Ejemplo n.º 22
0
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 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)
                 
Ejemplo n.º 24
0
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')
Ejemplo n.º 25
0
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
Ejemplo n.º 26
0
    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
Ejemplo n.º 27
0
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)
Ejemplo n.º 28
0
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
Ejemplo n.º 29
0
            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())


# test
test_q = LinkedQueue()
test_list = [9, 10, 8, 7, 100, 34, 33, 38]
for element in test_list:
    test_q.enqueue(element)

quick_sort(test_q)

while not test_q.is_empty():
    ele = test_q.dequeue()
    print (ele)
    
Ejemplo n.º 30
0
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())
Ejemplo n.º 31
0
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())
Ejemplo n.º 32
0
from linked_queue import LinkedQueue

queue = LinkedQueue()
queue.print()

queue.put(1)
queue.put(2)
queue.put(3)
queue.put(4)
queue.put(5)
queue.put(6)
queue.print()

print(queue.get())
print(queue.get())
print(queue.get())
print(queue.get())
queue.print()

queue.put(4)
queue.put(5)
queue.put(6)
queue.print()

print(queue.get())
print(queue.get())
print(queue.get())
queue.print()
Ejemplo n.º 33
0
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())
Ejemplo n.º 34
0
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())
Ejemplo n.º 35
0
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())
Ejemplo n.º 36
0
    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)