def transform_bfs(start, target, h, t, flag):
    q = Queue()
    q.push(Word(start, True))
    counter = 0

    while not q.is_empty() and counter <= t:
        word = q.pop()
        options = generate_options(word.str)
        for opt in options:
            if opt in h:
                for candidate in h[opt]:
                    if candidate.visited != flag:
                        if candidate.visited == False:
                            if compare(candidate.str, target) == 1:
                                return word.ancestry + [
                                    word.str, candidate.str, target
                                ]
                            else:
                                candidate.visited = flag
                                candidate.ancestry = word.ancestry + [word.str]
                                q.push(candidate)
                                counter += 1
                        else:
                            return word.ancestry + [
                                word.str, candidate.str
                            ] + candidate.ancestry[::-1]
    return None
Пример #2
0
 def test_dequeue(self):
     q = Queue(['A', 'B', 'C'])
     assert q.dequeue() == 'A'
     assert q.length() == 2
     assert q.dequeue() == 'B'
     assert q.length() == 1
     assert q.dequeue() == 'C'
     assert q.length() == 0
     assert q.is_empty() is True
     with self.assertRaises(ValueError):
         q.dequeue()
Пример #3
0
def bfs(land, r, c, rows, cols):
    q = Queue()
    land[r][c] = False
    q.push((r, c))
    while not q.is_empty():
        x, y = q.pop()
        for i, j in [(x, y + 1), (x, y - 1), (x + 1, y), (x - 1, y)]:
            if i in range(rows) and j in range(cols) and land[i][j]:
                land[i][j] = False
                q.push((i, j))
    return
Пример #4
0
 def test_enqueue(self):
     q = Queue()
     q.enqueue('A')
     assert q.front() == 'A'
     assert q.length() == 1
     q.enqueue('B')
     assert q.front() == 'A'
     assert q.length() == 2
     q.enqueue('C')
     assert q.front() == 'A'
     assert q.length() == 3
     assert q.is_empty() is False
Пример #5
0
    def bfs(gui, one_step=False):
        starting_pos = gui.grid.head.get_node()
        fringe = Queue()
        # Fringe holds a list of tuples: (node position, move to get prev to current, cost)
        fringe.enqueue([(starting_pos, None, 0)])
        path = []
        visited = [starting_pos]
        while not fringe.is_empty():
            # Get the next one to be popped off the stack to search it's neighbor nodes (successors)
            path = fringe.dequeue()

            if gui.grid.grid[path[-1][0][0]][path[-1][0][1]] == 3:
                break

            for neighbor in get_neighbors(gui, path[-1][0][0], path[-1][0][1]):
                if neighbor[0] not in visited:
                    updated_path = copy.copy(path)
                    updated_path.append(neighbor)
                    fringe.enqueue(updated_path)
                    if not gui.grid.grid[neighbor[0][0]][neighbor[0][1]] == 3:
                        visited.append(neighbor[0])

        if not fringe.is_empty():
            move_set = []
            while path:
                temp = path.pop(0)
                if temp[1] is not None:
                    move_set.append(temp[1])
            if not one_step:
                return move_set
            else:
                return [move_set[0]]
        else:
            no_bfs_move = go_furthest(gui)
            if no_bfs_move:
                return no_bfs_move
            else:
                no_moves_at_all = go_down()
                return no_moves_at_all
Пример #6
0
 def levelorder(self):
     items = []
     queue = Queue()
     node = self._root  # starting from the root
     queue.insert(node)  # insert it
     while not queue.is_empty():
         node = queue.remove()  # pick that node
         items.append(node._data)  # add to the list
         # if the left side is not None, there exist a left side, add the queue (going left to right_
         if node._left is not None:
             queue.insert(node._left)
         # you also want to add the right side
         if node._right is not None:
             queue.insert(node._right)
     return items
def breadth_first_search_adjlist(graph, source, destination):
    if not source in graph.vertices:
        print('Source does not exist in graph')
        return
    if not destination in graph.vertices:
        print('destination does not exist in graph')
        return

    #Set inital parameters for source vert, enqueue source
    graph.vertex_object[source].color = 'grey'
    graph.vertex_object[source].distance = 0
    graph.vertex_object[source].prev_search = None

    bfs_queue = Queue()
    bfs_queue.enqueue(source)

    #BFS while loop. Search closest nodes and set distances from source/build tree
    while not bfs_queue.is_empty():
        current_vert = graph.vertex_object[bfs_queue.dequeue()]
        print(current_vert.name)
        for vertex in graph.vertices[current_vert.name]:
            if graph.vertex_object[vertex].color == 'white':
                graph.vertex_object[vertex].color = 'grey'
                graph.vertex_object[
                    vertex].distance = current_vert.distance + 1
                graph.vertex_object[vertex].prev_search = current_vert.name
                bfs_queue.enqueue(vertex)

                print('Vertex:' + vertex)

    vertex_iterator = graph.vertex_object[destination]
    bfs_stack = []

    while vertex_iterator != graph.vertex_object[source]:
        if not vertex_iterator.prev_search:
            print('No path between source and destination')
            return

        bfs_stack.append(vertex_iterator.name)
        vertex_iterator = graph.vertex_object[vertex_iterator.prev_search]

    bfs_stack.append(source)

    print([x for x in reversed(bfs_stack)])
Пример #8
0
    def __str__(self):
        """
        -------------------------------------------------------
        Description:
            Returns a string representation of bst
            Uses Breadth First Search (BFS)
        Assert: none
        Use: str(bst) or print(bst)
        -------------------------------------------------------
        Parameters:
            None
        Returns:
            output: string representation of bst (str)
        -------------------------------------------------------
        """
        q = Queue(self.MAX_SIZE)
        output = ''

        q.insert(self._root)
        level = 1

        while not q.is_empty():
            node = q.remove()

            if node is None:
                continue

            node_level = self.level(node._data)

            if node_level == level:
                output += '{} '.format(str(node._data))

            elif node_level > level:
                output = '{}\n'.format(output[:-1])
                output += '{} '.format(str(node._data))
                level += 1

            if node._left is not None:
                q.insert(node._left)

            if node._right is not None:
                q.insert(node._right)

        return output[:-1]
Пример #9
0
    def _reflect_vertical_aux(self, node):
        queue = Queue()
        tree = BST()

        if node is None:
            return tree

        if node is not None:
            queue.insert(node)
        while not queue.is_empty():
            temp = node._left
            node._left = node._right
            node._right = temp
            node = queue.remove()
            tree.insert(node._data)
            if node._left is not None:
                queue.insert(node._left)
            if node._right is not None:
                queue.insert(node._right)

        return tree
Пример #10
0
 def __str__(self):
     """
     -------------------------------------------------------
     Description:
         Returns a string representation of bst
         Uses Breadth First Search (BFS)
     Assert: none
     Use: str(bst) or print(bst)
     -------------------------------------------------------
     Parameters:
         None
     Returns:
         output: string representation of bst (str)
     -------------------------------------------------------
     """
     # You can all the way down print the depth (DFS depth first search) --> Stacks
     # Horizontal search, reads horizontally to prints (BFS breath first search) --> Queues
     q = Queue(self.MAX_SIZE)
     output = ''
     q.insert(self._root)
     level = 1
     # come back to this in WEEK #11
     while not q.is_empty():
         node = q.remove()
         if node is None:
             continue
         node_level = self.level(node._data)
         if node_level == level:
             output += str(node._data) + ' '
         elif node_level > level:
             output = output[:-1] + '\n'
             output += str(node._data) + ' '
             level += 1
         if node._left is not None:
             q.insert(node._left)
         if node._right is not None:
             q.insert(node._right)
     return output[:-1]
Пример #11
0
def reverse_stack(stack):
    """
    -------------------------------------------------------
    Description:
        Reverse a stack using a queue
    Use: reverse_stack(stack)
    -------------------------------------------------------
    Parameters:
        stack - a stack of items (Stack)
    Returns:
        No returns
    -------------------------------------------------------
    """
    queue = Queue()
    
    while not stack.is_empty():
        item = deepcopy(stack.pop())
        queue.insert(item)
    
    while not queue.is_empty():
        stack.push(queue.remove())

    return
Пример #12
0
class AnimalShelter:
    def __init__(self):
        self.dogs = Queue()
        self.cats = Queue()
        self.counter = 0

    def enqueue(self, *, name, species):
        if species in Animal.VALID_SPECIES:
            self.counter += 1
            getattr(self, f"{species}s").push(
                Animal(name=name, species=species, counter=self.counter))
        else:
            raise AttributeError("INVALID TYPE")

    def dequeue_cat(self):
        if self.cats.is_empty():
            raise IndexError("EMPTY CAT QUEUE")
        else:
            return self.cats.pop().name

    def dequeue_dog(self):
        if self.dogs.is_empty():
            raise IndexError("EMPTY DOG QUEUE")
        else:
            return self.dogs.pop().name

    def dequeue_any(self):
        if self.dogs.is_empty() and self.cats.is_empty():
            raise IndexError("EMPTY QUEUE")
        elif self.dogs.is_empty():
            return self.dequeue_cat()
        elif self.cats.is_empty():
            return self.dequeue_dog()
        else:
            return self.dequeue_cat() if self.dogs.peek(
            ).counter > self.cats.peek().counter else self.dequeue_dog()
Пример #13
0
 def test_nowa_kolejka_jest_pusta(self):
     q = Queue()
     self.assertTrue(q.is_empty())
Пример #14
0
from my_queue import Queue

q = Queue(3)
assert (q.is_empty())
assert (hasattr(q, "items"))
assert (hasattr(q, "insert"))
assert (hasattr(q, "remove"))
assert (hasattr(q, "is_empty"))

result = q.insert(5)
assert (result == True)
assert (not q.is_empty())
assert (q.__str__() == "5")

result = q.insert(7)
assert (result == True)
assert (not q.is_empty())
assert (q.__str__() == "7 5")

result = q.insert(-1)
assert (result == True)
assert (not q.is_empty())
assert (q.__str__() == "-1 7 5")

result = q.insert(20)
assert (result == False)
assert (not q.is_empty())
assert (q.__str__() == "-1 7 5")

result = q.insert(33)
assert (result == False)
Пример #15
0
def test_is_empty():
    queue = Queue()
    assert queue.is_empty() is True

    queue.enqueue(1)
    assert queue.is_empty() is False
Пример #16
0
    '''------------Second Part--------------'''
    # user enters str values into stack
    line = input("Enter a string,'end' to stop: ")
    while (line != 'end'):
        stack.push(line)
        line = input("Enter a string,'end' to stop:")

    # user typed str values are removed from stack and printed
    while not(stack.is_empty()):
        print(stack.pop())

    '''-------------Third Part----------------'''
    # same user interaction as before, except use a Queue instead of Stack
    queue = Queue()
    line = int(input("Enter a string,'end' to stop: "))
    while (line != 'end'):
        queue.enqueue(line)

        #convert line to an int unless it is 'end'
        line = (input("Enter a string,'end' to stop:"))
        if  line != 'end':
        	line = int(line)

    product = 1
    while not(queue.is_empty()):
        product *= queue.dequeue()

    print(product)

    
Пример #17
0
 def test_init(self):
     q = Queue()
     assert q.front() is None
     assert q.length() == 0
     assert q.is_empty() is True
Пример #18
0
 def test_init_with_list(self):
     q = Queue(['A', 'B', 'C'])
     assert q.front() == 'A'
     assert q.length() == 3
     assert q.is_empty() is False
Пример #19
0
 def test_po_dodaniu2_i_usunieciu1_elementu_kolejka_nie_jest_pusta(self):
     q = Queue()
     q.enqueue(123)
     q.enqueue(456)
     q.dequeue()
     self.assertFalse(q.is_empty())
Пример #20
0
 def test_po_dodaniu_i_usunieciu_elementu_kolejka_jest_pusta(self):
     q = Queue()
     q.enqueue(123)
     q.dequeue()
     self.assertTrue(q.is_empty())
Пример #21
0
 def test_po_dodaniu_elementu_kolejka_nie_jest_pusta(self):
     q = Queue()
     q.enqueue(123)
     self.assertFalse(q.is_empty())