예제 #1
0
def parse_args_graph(args):
    if args.route_type == 'dsf':
        graph.dsf(graph.N, 0, 1000)
    elif args.route_type == 'bfs':
        graph.bfs(graph.N, 0, 1000)
    else:
        print('Unknown type of route')
예제 #2
0
파일: main.py 프로젝트: dgcnz/grakn-twitter
def main():
    check_rate_limit()

    user_id, user_name = get_current_id_name()
    root = Node(user_id, user_name)
    root = dfs(root, get_next_mutuals, 2)
    bfs(root, lambda v: v.neighbors, print, 3)
    check_rate_limit()

    grakn_save(root)
예제 #3
0
파일: testgraph.py 프로젝트: altoid/graph
    def test_bfs(self):

        gr = graph.UGraph()
        a = graph.Node('a')
        b = graph.Node('b')
        c = graph.Node('c')
        d = graph.Node('d')
        e = graph.Node('e')
        f = graph.Node('f')
        g = graph.Node('g')
        h = graph.Node('h')

        gr.addnodes(a, b, c, d, e, f, g, h)
        
        gr.addedge(a, b)
        gr.addedge(a, g)
        gr.addedge(a, d)

        gr.addedge(b, e)
        gr.addedge(b, f)

        gr.addedge(c, f)
        gr.addedge(c, h)

        gr.addedge(d, f)
        gr.addedge(e, g)

        r = graph.bfs(gr, a)
        self.assertEqual('abdgefch', r)
예제 #4
0
파일: testgraph.py 프로젝트: altoid/graph
    def test_bfs_simple(self):

        # graph with one vertex and no edges
        # graph with one vertex and one (loop) edge

        gr = graph.UGraph()
        a = graph.Node('a')
        
        outsider = graph.Node('mr_lonely')
        
        with self.assertRaises(graph.GraphException):
            graph.bfs(gr, outsider)

        gr.addnode(a)
        gr.addedge(a, a)

        graph.bfs(gr, a)
    def buildGraph(self):
        '''
        练习22.2-1

        练习22.2-2
        '''
        g = _g.Graph()
        g.veterxs = [_g.Vertex('1'), _g.Vertex('2'),
                     _g.Vertex('3'), _g.Vertex('4'),
                     _g.Vertex('5'), _g.Vertex('6')]
        g.edges.clear()
        g.edges.append(_g.Edge(_g.Vertex('1'), _g.Vertex('2'), 1, _g.DIRECTION_TO))
        g.edges.append(_g.Edge(_g.Vertex('4'), _g.Vertex('2'), 1, _g.DIRECTION_TO))
        g.edges.append(_g.Edge(_g.Vertex('1'), _g.Vertex('4'), 1, _g.DIRECTION_TO))
        g.edges.append(_g.Edge(_g.Vertex('2'), _g.Vertex('5'), 1, _g.DIRECTION_TO))
        g.edges.append(_g.Edge(_g.Vertex('3'), _g.Vertex('6'), 1, _g.DIRECTION_TO))
        g.edges.append(_g.Edge(_g.Vertex('3'), _g.Vertex('5'), 1, _g.DIRECTION_TO))
        g.edges.append(_g.Edge(_g.Vertex('5'), _g.Vertex('4'), 1, _g.DIRECTION_TO))
        g.edges.append(_g.Edge(_g.Vertex('6'), _g.Vertex('6'), 1, _g.DIRECTION_TO))
        _g.bfs(g, g.veterxs[2])
        _g.print_path(g, g.veterxs[2], g.veterxs[4])
        print('')
        del g
        
        g = _g.Graph()
        g.veterxs.clear()
        g.edges.clear()
        v = ['r', 's', 't', 'u', 'v', 'w', 'x', 'y']
        g.addvertex(v)
        g.addedge('v', 'r')
        g.addedge('r', 's')
        g.addedge('s', 'w')
        g.addedge('w', 'x')
        g.addedge('w', 't')
        g.addedge('x', 't')
        g.addedge('x', 'u')
        g.addedge('x', 'y')
        g.addedge('y', 'u')
        g.addedge('u', 't')
        _g.bfs(g, 'u')
        _g.print_path(g, 'u', 'v')
        print('')
        del g
예제 #6
0
def Executioner(file):
    w = {}
    f = open("dictionary.txt")  #opening the dictionary file
    dicwords = f.read().split(
        '\n')  #reading the words from dictionary and then spliting them

    for eachword in dicwords:
        for word in dicwords:
            if eachword in Graph:
                start = Graph[eachword]
                if word in Graph:
                    if (eachword != word):
                        finish = Graph[word]

                        predecessors = bfs(start, finish, Graph)
                        if (predecessors != ''):
                            path = getPath(start, finish, predecessors)
                            str = ''
                            array.append(path)
                            for p in path:
                                str += p + ' -> '
                            print(str[:-3])
예제 #7
0
def word_ladder(start, stop, dictionary):
    if start not in dictionary or stop not in dictionary:
        raise ValueError("Dictionary missing start or stop")
    g = collections.defaultdict(set)
    buckets = collections.defaultdict(set)
    for word in dictionary:
        for i in range(len(word)):
            bucket = word[:i] + '_' + word[i+1:]
            buckets[bucket].add(word)
    for bucket_words in buckets.itervalues():
        for word in bucket_words:
            neighbours = bucket_words.difference([word])
            g[word].update(neighbours)
    # to prevent surprises w/ defaultdict
    g = dict(g)
    (_, pred) = graph.bfs(g, start)
    if stop not in pred:
        raise ValueError("Stop is not reachable")
    p = pred[stop]
    path = [stop, p]
    while p != start:
        p = pred[p]
        path.append(p)
    return list(reversed(path))
예제 #8
0
collums_coordinats = qr[:-3]
#read the code data to variables
X = float(qr[-3])
Y = float(qr[-2])
n = float(qr[-1])
obs = []
factor = 10
#read column data
for i in range(0, len(collums_coordinats), 2):
    print("Column area x=" + str(collums_coordinats[i]) + ", y=" + str(collums_coordinats[i + 1]))
    obs.append([[float(collums_coordinats[i])*factor,float(collums_coordinats[i + 1])*factor],0.5*factor])
print("Navigate area x= " + str(X) + ", y=" + str(Y)) 
print("Order number: " + str(n))

#compute array for navigation and avoidance using  breadth-first search
m = bfs([int(X*factor),int(Y*factor)],obs)

#fly to arrow using found array
xc = 2
yc = 2
while(m[xc][yc][0] >= 0):
    xc,yc = m[xc][yc][0],m[xc][yc][1]
    fly(xc/factor,yc/factor)
if(m[xc][yc][0] == -1):
    print("oops")
fly(X, Y, 0.6)
fly(X, Y, 1.2)


img = bridge.imgmsg_to_cv2(rospy.wait_for_message('main_camera/image_raw', Image), 'bgr8')
try:
예제 #9
0
# file for testing the different functions in pyalgos

import graph

if __name__ == "__main__":
    src = 0
    G = [[1, 2, 4], [], [3, 4, 5], [], [3, 5], []]
    print("graph.bfs({0}, {1},\n          get_path = True) ->\n{2}".format(
        src, G, graph.bfs(src, G, get_path=True)))
    G = [[False, True, True, False, True, False],
         [False, False, False, False, False, False],
         [False, False, False, True, True, True],
         [False, False, False, False, False, False],
         [False, False, False, True, False, True],
         [False, False, False, False, False, False]]
    print("graph.bfs({0}, {1},\n          is_adjm = True, get_path = True,) ->"
          "\n{2}".format(src, G, graph.bfs(src, G, is_adjm=True,
                                           get_path=True)))
예제 #10
0
def test_all_alg():
    """
    Test all algorithms dfs, bfs, and a* with all heuristics used
    on a single randomly generated 8 puzzle
    """
    print("Testing all algorithms on a random 8 puzzle")
    random_puzzle = _gen_1_puzzle(3, EIGHT_PSOL)
    printPuzzle(random_puzzle)

    print("\nTesting DFS")
    start_time = time.time()
    states_taken, final = dfs(random_puzzle, EIGHT_PSOL)
    if final is None:
        print("Error this puzzle is not solvable trying again\n")
        test_all_alg()
        return
    print("%s seconds to solve with DFS" % (time.time() - start_time))
    print("{} steps to find the solution".format(states_taken))
    print("{} steps for the simple path to the solution".format(
        final.num_parents))
    print("\n----------- End DFS Testing ---------------\n")

    print("Testing BFS")
    start_time = time.time()
    states_taken, final = bfs(random_puzzle, EIGHT_PSOL)
    print("%s seconds to solve with BFS" % (time.time() - start_time))
    print("{} steps to find the solution".format(states_taken))
    print("{} steps for the simple path to the solution".format(
        final.num_parents))
    print("\n----------- End BFS Testing ---------------\n")

    print("Testing A* with Hamming Heuristic")
    start_time = time.time()
    states_taken, final = a_star(random_puzzle, EIGHT_PSOL, hamming_distance)
    print("%s seconds to solve with A* Hamming Distance Heuristic" %
          (time.time() - start_time))
    print("{} steps to find the solution".format(states_taken))
    print("{} steps for simple path to the solution".format(final.num_parents))
    print("\n----------- End A* Hamming Testing ---------------\n")

    print("Testing A* with Manhattan Heuristic")
    start_time = time.time()
    states_taken, final = a_star(random_puzzle, EIGHT_PSOL, manhattan_distance)
    print("%s seconds to solve with A* with Manhattan Distance Heuristic" %
          (time.time() - start_time))
    print("{} steps to find the solution".format(states_taken))
    print("{} steps for the simple path to the solution ".format(
        final.num_parents))
    print("\n----------- End A* Manhattan Testing ---------------\n")

    print("Testing A* with Linear Conflict Heuristic")
    start_time = time.time()
    states_taken, final = a_star(random_puzzle, EIGHT_PSOL, linear_conflict)
    print("%s seconds to solve with A* with Linear Conflict Heuristic" %
          (time.time() - start_time))
    print("{} steps to find the solution".format(states_taken))
    print("{} steps for simple path to the solution".format(final.num_parents))
    print("\n----------- End A* Manhattan Testing ---------------\n")

    print("Now showing simple path to solution")
    print("Initial state of the puzzle")
    printPuzzle(random_puzzle)
    print("-------------")
    path = reconstruct_path(final)
    for next in path:
        print("Take {} from previous puzzle".format(next.direction))
        printPuzzle(next.state)
        print("-------------")
    print("Final State above")
예제 #11
0
    # Taking input from Users for two words to make a word ladder
    fword = raw_input('Enter the first word :')
    sword = raw_input('Enter the second word :')

    if len(sys.argv) > 1:

        fword = sys.argv[1]
        sword = sys.argv[2]

    if fword in Graph:

        start = Graph[fword]

        if sword in Graph:
            finish = Graph[sword]
            predecessors = bfs(start, finish,
                               Graph)  #calling bfs function from graph.py
            path = getPath(
                start, finish,
                predecessors)  #calling getpath function from graph.py
            str = ''

            for p in path:

                str += p + ' -> '  #printing the chain by replacing letters from first word to second

            print(str[:-3])

        else:
            print("Second Word is not found in Graph")

    else:
예제 #12
0
def test_invalid_traversal(graph):
    with pytest.raises(ValueError):
        dfs(graph)
    with pytest.raises(ValueError):
        bfs(graph)
예제 #13
0
def test_bfs_simple(graph, expected):
    actual = [node.data for node in bfs(graph)]
    assert actual == expected
예제 #14
0
# run a* algorithm
paths_distances_and_swags, count = a_star(grid, start_i, start_j, end_i, end_j)

print("\n" + colors.CBLUE2 + "   ## A star ## " + colors.CEND)
print_maze_paths(grid, paths_distances_and_swags[end_i][end_j][1])

# Debug only
#print("\ndistances with hueristic for each cell:\n")
#for row in paths_distances_and_swags:
#    for column in row:
#        if column[0] == inf:
#            column[0] = "|||"
#        print("{:3.3}".format(str(column[0])), end = " ")
#    print(" ")
#print("\nDistance from Start to End is {0}".format(paths_distances_and_swags[end_i][end_j][0]))
print("Found the end of the in the {0} steps with length of {1}".format(count, len(paths_distances_and_swags[end_i][end_j][1])))
#print("Path from Start to End: \n{0}".format(paths_distances_and_swags[end_i][end_j][1]))

print("\n" + colors.CBLUE2 + "   ## BFS ## " + colors.CEND)
paths_and_swags, count = bfs(grid, start_i, start_j, swags)
print_maze_paths(grid, paths_and_swags[end_i][end_j][0])
print("Found the end of the in the {0} steps with length of {1}".format(count, len(paths_and_swags[end_i][end_j][0])))


swag_list = paths_distances_and_swags[end_i][end_j][2]
print("\nSwags collected along the way: \n{0}".format(swag_list))
quicksort(swag_list, 0, len(swag_list) - 1)
print("Sorted Swag list by quick sort: \n{0}".format(swag_list))

#print("\n\nShortest Distances: {0}".format(distances))