Ejemplo n.º 1
0
import fileinput,graphs
 
# add_edge (u -> v) with weight w to graph
def add_edge(graph,u,v,w):
        if u in graph:                  #vertex u already in graph?
		l = graph[u]            #get list of neighbours
	else:
		graph[u] = l = list()	#insert u into graph and assign an empty list of neighbours
	l.append((v,w))                 #append tuple (v,w) into the neighbour list
	
 
g = dict()                              #initialize graph
for line in fileinput.input():
	u,v,w = map(int,line.split())
	add_edge(g,u,v,w)
	add_edge(g,v,u,w)               #undirected graph, edges go both ways
	
print graphs.bidirectional_dijkstra(g,1,5,undirected=True)        #from wikipedia
Ejemplo n.º 2
0
import sys,graphs,itertools

def prepare_graph():
    diff_by_1 = lambda (x,y): len(x) == len(y) and sum(1 for a,b in zip(x,y) if a != b) == 1
    graph = {}
    for x,y in filter(diff_by_1,itertools.product(words,repeat=2)):
        if x not in graph: graph[x] = []
        if y not in graph: graph[y] = []
        graph[x].append( ( y , 1) )
        graph[y].append( ( x , 1) )
    return graph

if __name__ == '__main__':
    if len(sys.argv) >= 3 and  len(sys.argv[1]) == len(sys.argv[2]):
        src,dst = sys.argv[1:]
        words = filter(lambda w : len(w) == len(src), sys.stdin.read().split()) #only consider those words with same length as parameter
        if src in words and dst in words:
            print graphs.bidirectional_dijkstra(prepare_graph(),src,dst,undirected=True)
        else:
            print "Both words should be present in the dictionary."
    else:
        print "Missing command line parameters."
Ejemplo n.º 3
0

def prepare_graph():
    diff_by_1 = lambda (x, y): len(x) == len(y) and sum(1
                                                        for a, b in zip(x, y)
                                                        if a != b) == 1
    graph = {}
    for x, y in filter(diff_by_1, itertools.product(words, repeat=2)):
        if x not in graph: graph[x] = []
        if y not in graph: graph[y] = []
        graph[x].append((y, 1))
        graph[y].append((x, 1))
    return graph


if __name__ == '__main__':
    if len(sys.argv) >= 3 and len(sys.argv[1]) == len(sys.argv[2]):
        src, dst = sys.argv[1:]
        words = filter(
            lambda w: len(w) == len(src),
            sys.stdin.read().split(
            ))  #only consider those words with same length as parameter
        if src in words and dst in words:
            print graphs.bidirectional_dijkstra(prepare_graph(),
                                                src,
                                                dst,
                                                undirected=True)
        else:
            print "Both words should be present in the dictionary."
    else:
        print "Missing command line parameters."