def mst(matrix, s): for i in range(len(matrix)): matrix[i][i] = sys.maxint graph = Graph() for i in range(len(matrix)): for j in range(len(matrix)): graph.addEdge(i, j, matrix[i][j]) prim(graph, graph.getVertex(s)) sum = 0 for each in graph: sum += each.getDistance() return sum
def build_graph(word_file) -> Graph: g = Graph() bucket = defaultdict(list) with open(word_file) as f: for line in f: word = line.strip() for i in range(len(word)): key = word[:i] + '_' + word[i + 1:] # 下划线表示通配符 bucket[key].append(word) # 将只有一个字母不同的单词放入同一个桶中 # 将同一个桶中的所有单词进行连接 for words in bucket.values(): for i in range(n := len(words)):
def knightGraph(bdSize): ktGraph = Graph() for row in range(bdSize): for col in range(bdSize): nodeId = posToNodeId(row, col, bdSize) newPositions = genLegalMoves(row, col, bdSize) for e in newPositions: nid = posToNodeId(e[0], e[1], bdSize) ktGraph.addEdge(nodeId, nid) path = [] limit = bdSize * bdSize currentVertex = ktGraph.getVertex(0) x = knightTour(0, path, currentVertex, limit) y = path
def main(args): # TODO: add proper TESTs to initialize Graph and Vertex with graph example from GeeksForGeeks! # print type(Graph) # print dir(Graph) # print type(Vertex) # print dir(Vertex) # help(Vertex.__init__) # print dir(PriorityQueue) vertex0 = Vertex(0) vertex0.setDistance(0) # print vertex0 vertex1 = Vertex(1) # print vertex1 vertex7 = Vertex(7) # print vertex7 vertex2 = Vertex(2) # print vertex2 graph1 = Graph() graph1.addVertex(vertex0) graph1.addVertex(vertex1) graph1.addVertex(vertex7) graph1.addVertex(vertex2) print 'Initialized Vertex Dump:' # for aVertex in graph1.getVertices(): # print aVertex print 'Initialized Edges Dump:' graph1.addEdge(vertex0, vertex1, 4) graph1.addEdge(vertex0, vertex7, 8) graph1.addEdge(vertex1, vertex2, 8) print 'Vertex Sequenced after Djikstra from starting point with key 0' try: dijkstra(graph1, vertex0) for aVertex in graph1.getVertices(): print aVertex except Exception as ex: logging.exception("BURP!")
def buildGraph(word): d = {} g = Graph() for n in range(len(word)): bucket = word[:n] + "_" + word[n + 1:] if bucket in d: d[bucket].append(word) else: d[bucket] = [word] for bucket in d.keys(): for word1 in d[bucket]: for word2 in d[bucket]: if word1 != word2: g.addEdge(word1, word2) return g
def build_graph(words): dictionary = {} g = Graph() for word in words: for i in range(len(word)): group = word[:i] + '_' + word[i + 1:] if group in dictionary: dictionary[group].append(word) else: dictionary[group] = [word] for group in dictionary.keys(): for word1 in dictionary[group]: for word2 in dictionary[group]: if word1 != word2: g.addEdge(word1, word2) return g
def bfs(g, start): g = Graph() start = Vertex() start.setDistance(0) start.setPred(None) vertQueue = Queue() vertQueue.enqueue(start) while vertQueue.size() > 0: currentVert = vertQueue.dequeue() for nbr in currentVert.getConnections(): if nbr.getColor() == 'white': nbr.setColor('gray') nbr.setDistance(currentVert.getDistance() + 1) nbr.setPred(currentVert) vertQueue.enqueue(nbr) currentVert.setColor('black')
def buildGraph(wdict): d = {} g = Graph() for word in wdict: for i in range(len(word)): bucket = word[:i] + '_' + word[i + 1:] if bucket in d: d[bucket].append(word) else: d[bucket] = [word] for bucket in d.keys(): for word1 in d[bucket]: for word2 in d[bucket]: if word1 != word2: g.addEdge(word1, word2) return g
def buildGraph(wordFile): d = {} g = Graph() wfile = open(wordFile, 'r') for line in wfile: word = line[:-1] for i in range(len(word)): bucket = word[:i] + '_' + word[i + 1:] if bucket in d: d[bucket].append(word) else: d[bucket] = [word] for bucket in d.keys(): for word1 in d[bucket]: for word2 in d[bucket]: if word1 != word2: g.addEdge(word1, word2) return g
def build_graph(word_list): d = {} g = Graph() # create buckets of words that differ by one letter for word in word_list: for i in range(len(word)): bucket = word[:i] + '_' + word[i + 1:] if bucket in d: d[bucket].append(word) else: d[bucket] = [word] # add vertices and edges for words in the same bucket for bucket in d.keys(): for word1 in d[bucket]: for word2 in d[bucket]: if word1 != word2: g.add_edge(word1, word2) return g
def buildGraph(wordFile): d = {} g = Graph() wfile = open(wordFile, 'r') # create buckets of words that differ by one letter for line in wfile: word = line[:-1] for i in range(len(word)): bucket = word[:i] + '_' + word[i + 1:] if bucket in d: d[bucket].append(word) else: d[bucket] = [word] # add vertices and edges for words in the same bucket for bucket in d.keys(): for word1 in d[bucket]: for word2 in d[bucket]: if word1 != word2: g.addEdge(word1, word2)
def buildGraph(wordFile): d = {} g = Graph() wfile = open(wordFile, 'r') lines = wfile.readlines() for line in lines: word = line.strip('\n') for i in range(len(word)): bucket = word[:i] + "_" + word[i + 1:] if bucket in d: d[bucket].append(word) else: d[bucket] = [word] for bucket in d.keys(): for word1 in d[bucket]: for word2 in d[bucket]: if word1 != word2: g.addEdge(word1, word2) return g
def buildGraph(): g = Graph() #g.addEdge('u','v', 2) #g.addEdge('u','x', 1) #g.addEdge('v','w', 3) #g.addEdge('w','z', -5) #g.addEdge('u','w', 5) #g.addEdge('v','x', 2) #g.addEdge('x','y', 1) #g.addEdge('y','z', 1) #g.addEdge('x','w', 3) #g.addEdge('y','w', 1) #Fig 4.14 from S Dasgupta g.addEdge('s', 'a', 10) g.addEdge('s', 'g', 8) g.addEdge('g', 'f', 1) g.addEdge('a', 'e', 2) g.addEdge('f', 'a', -4) g.addEdge('f', 'e', -1) g.addEdge('e', 'b', -4) g.addEdge('b', 'a', 1) g.addEdge('b', 'c', 1) g.addEdge('c', 'd', 3) g.addEdge('d', 'e', -1) pq = PriorityQueue() start = g.getVertex('s') start.setDistance(0) pq.buildHeap([(v.getDistance(), v) for v in g]) while not pq.isEmpty(): currentVert = pq.delMin() for nextVert in currentVert.getConnections(): newDist = currentVert.getDistance() \ + currentVert.getWeight(nextVert) if newDist < nextVert.getDistance(): nextVert.setDistance(newDist) nextVert.setPred(currentVert) pq.decreaseKey(nextVert, newDist) return g
def buildGraph(wordFile): d = {} g = Graph() with open(wordFile, 'r') as f: # 1 create bucket for line in f: word = line[:-1] for i in range(len(word)): bucket = word[:i] + '_' + word[i+1:] if bucket in d: d[bucket].append(word) else: d[bucket] = [word] # 2 add vertices and edges for bucket in d.keys(): for word1 in d[bucket]: for word2 in d[bucket]: if word1 != word2: g.add_edge(word1, word2) return g
def build_graph(word_file): d = {} g = Graph() with open(word_file) as f: for line in f: word = line.strip() for i in range(len(word)): bucket = word[:i] + '_' + word[i + 1:] if bucket in d: d[bucket].append(word) else: d[bucket] = [word] for bucket, words in d.items(): for word1 in words: for word2 in words: if word1 != word2: g.add_edge(word1, word2) return g
def buildGraph(file): bucket = {} wordGraph = Graph() # 构建词桶 with open(file, 'r') as wordFile: for word in wordFile: word = word.strip('\n') # 去除每一行的换行符 for i in range(len(word)): underlineWord = word[:i] + '_' + word[i + 1:] if underlineWord in bucket: bucket[underlineWord].append(word) else: bucket[underlineWord] = [word] # 为词桶里每个词创建边 for underlineWord in bucket.keys(): for word1 in bucket[underlineWord]: for word2 in bucket[underlineWord]: if word1 != word2: wordGraph.addEdge(word1, word2) return wordGraph
def buildGraph(wordFile): d = {} g = Graph() wfile = open(wordFile, "r") # 创建只有一个单词不同的桶 for line in wfile: word = line[:-1] for i in range(len(word)): bucket = word[:i] + "_" + word[i + 1:] if bucket in d: d[bucket].append(word) else: d[bucket] = [word] # 为同一个桶里面的单词添加顶点和边 for bucket in d.keys(): for word1 in d[bucket]: for word2 in d[bucket]: if word1 != word2: g.addEdge(word1, word2) return g
def build_graph(wordlist): """ 假设我们有非常多的桶,每个桶外都贴有一个四个字母的 单词标签,并且标签上有且仅有一个字母被‘ _’(通配符)所代替。 例如,考虑图 7.6,我们就可能 会将一个桶贴上“ pop_”, 当我们处理我们的列表中的每个词,都将其与每个桶比较,使用“_” 作为一个通配符, 那么“pope” 和“ pops” 都与“ pop_”匹配。每次我们找到一个匹配的桶,我 们把单词放在桶里。 一旦我们把所有单词都放在适当的桶里,我们便知道,同一个桶里的所有单词 都是相互连接的。 我们可以通过使用一个字典来实现我们刚刚描述的方案。我们刚刚提到的桶上 的标签在我们的字典中作为 key,键值 value 是标签对应的单词列表。 一旦我们创建了字典我们就 可以生成图。 原因: 我们为这个 问题准备的 4 个字母的单词列表足足有 5110 个单词那么长。如果我们要使用一个邻接矩阵存储, 矩阵会共有 5110*5110=26112100 个格子。 由 buildGraph 函数构建出来的图只有 53286 条边, 所以矩阵将只有 0.20%的格子被填充了 这个图的确是非常稀疏的。 """ d = {} # 存桶的 dict g = Graph() words = open(wordlist, "r") # create buckets of words that differ by one letter for lines in words: word = lines[:-1] for i in range(len(word)): bucket = word[:i] + "_" + word[i + 1:] if bucket in d: d[bucket].append(word) else: d[bucket] = [word] # add vertices and edges for words in the same bucket for bucket in d.keys(): for word1 in d[bucket]: for word2 in d[bucket]: if word1 != word2: g.addEdge(word1, word2) return g
def buildGraph(filename): movieDict = {} # actorDict = {} # probably not needed, mainly for testing numVertices vs num of Actors graph = Graph() with open(filename, 'r') as f: moviereader = csv.reader(f, delimiter='|') for row in moviereader: actor = row[1] movie = row[0] if movie in movieDict: movieDict[movie].append(actor) else: movieDict[movie] = [actor] for movie in movieDict.keys(): for actor1 in movieDict[movie]: for actor2 in movieDict[movie]: if actor1 != actor2: graph.addEdge(actor1, actor2, movie) return graph
def build_graph(): graph = Graph() graph.addEdge('A', 'B', 2) graph.addEdge('B', 'A', 2) graph.addEdge('A', 'C', 3) graph.addEdge('C', 'A', 3) graph.addEdge('B', 'C', 1) graph.addEdge('C', 'B', 1) graph.addEdge('B', 'D', 1) graph.addEdge('D', 'B', 1) graph.addEdge('B', 'E', 4) graph.addEdge('E', 'B', 4) graph.addEdge('D', 'E', 1) graph.addEdge('E', 'D', 1) graph.addEdge('E', 'F', 1) graph.addEdge('F', 'E', 1) graph.addEdge('C', 'F', 5) graph.addEdge('F', 'C', 5) graph.addEdge('F', 'G', 1) graph.addEdge('G', 'F', 1) return graph
def buildGraph(wordFile): d = {} g = Graph() wfile = open(wordFile, 'r') # create buckets of words that differ by one letter for line in wfile: word = line[:-1] for i in range(len(word)): bucket = word[:i] + '_' + word[i + 1:] # label if bucket in d: d[bucket].append(word) # bucket is the key in dictionary else: d[bucket] = [word] # add vertices and edges for words in the same bucket for bucket in d.keys(): for word1 in d[bucket]: for word2 in d[bucket]: if word1 != word2: g.addEdge( word1, word2) # all the words in the bucket must be connected return g
def main(): #file opening alphabet = "abcdefghijklmnopqrstuvwxyz" #file parsing word = [] for line in fileinput.input(): x = line.strip() t = x.lower() word.append(t) fileinput.close() g = Graph() for i in word: vertlist = g.getVertices() if i not in vertlist: g.addVertex(i) #vert0 = g.getVertex(i) fhalf = shalf = [] tmp = [] for idx,ch in enumerate(i): l = list(i) for a in alphabet: l[idx] = a final = "".join(l) if final in word and final not in vertlist: g.addVertex(final) vertlist = g.getVertices() if final in word and final in vertlist: #vert1 = g.getVertex(final) g.addEdge(i, final) g.addEdge(final, i) go = g.getVertex(i) s = go.getConnections() print i, len(s) return 0
def build_graph(): graph = Graph() graph.addEdge('u', 'v', 2) graph.addEdge('v', 'u', 2) graph.addEdge('u', 'x', 1) graph.addEdge('x', 'u', 1) graph.addEdge('u', 'w', 5) graph.addEdge('w', 'u', 5) graph.addEdge('v', 'x', 2) graph.addEdge('x', 'v', 2) graph.addEdge('v', 'w', 3) graph.addEdge('w', 'v', 3) graph.addEdge('x', 'w', 3) graph.addEdge('w', 'x', 3) graph.addEdge('w', 'y', 1) graph.addEdge('y', 'w', 1) graph.addEdge('x', 'y', 1) graph.addEdge('y', 'x', 1) graph.addEdge('y', 'z', 1) graph.addEdge('z', 'y', 1) graph.addEdge('z', 'w', 5) graph.addEdge('w', 'z', 5) return graph
def minimum_spanning_tree(graph, initial_city): start_city = graph.getVertex(initial_city) heap = PriorityQueue() aux_list = [] solution = [] visited_nodes = [] new_graph = Graph() for conect in start_city.getConnections(): aux_list.append( (start_city.getWeight(conect), (start_city.id, conect.id))) visited_nodes.append(start_city.id) heap.buildHeap(aux_list) while not heap.isEmpty(): cur_pair = heap.delMin() cur_node = graph.getVertex(cur_pair[1]) if cur_node.id not in visited_nodes: solution.append(cur_pair) visited_nodes.append(cur_node.id) for conect in cur_node.getConnections(): if conect.id not in visited_nodes: heap.add( (cur_node.getWeight(conect), (cur_node.id, conect.id))) else: continue print('Solution: ' + str(solution)) for city_1, city_2 in solution: new_graph.addEdge(city_1, city_2, 0) return new_graph
from pythonds.basic import Queue def pathExists(start,end): vertexQueue=Queue() vertexQueue.enqueue(start) while (vertexQueue.size()>0): item=vertexQueue.dequeue() if item.getId()==end.getId(): print ("path exists") return True else: for vertex in item.getConnections(): if vertex.getColor()=="white": vertex.setColor("gray") vertexQueue.enqueue(vertex) return False g=Graph() data=True while data!=1000: data=input("enter tuple") if data!=1000: g.addEdge(data[0],data[1]) while(True): tuple=input("Please enter tuple u want to know the path") print pathExists(g.getVertex(tuple[0]),g.getVertex(tuple[1])) for vertex in g.getVertices(): g.getVertex(vertex).setColor("white")
def setUp(self): self.tGraph = Graph()
mse.append([currentvertex.get_id(), currentvertex.get_distance()]) currentvertex.set_visited() for childvertex in currentvertex.adjacent: #print childvertex.get_id() newcost = currentvertex.get_weight(childvertex) if childvertex in pq and newcost < childvertex.get_distance(): childvertex.set_distance(newcost) childvertex.set_previous(currentvertex) pq.decreaseKey(childvertex, newcost) for i in mse: print i g = Graph() g.add_edge('a', 'b', 2) g.add_edge('a', 'c', 3) g.add_edge('c', 'f', 5) g.add_edge('f', 'g', 1) g.add_edge('b', 'e', 4) g.add_edge('b', 'd', 1) g.add_edge('b', 'c', 1) g.add_edge('d', 'e', 1) print 'Graph data:' for v in g: for w in v.get_connections(): vid = v.get_id() wid = w.get_id()
import sys sys.setrecursionlimit(1000000000) from pythonds.graphs import Graph from pythonds.basic import Stack from pythonds.basic import Queue stk=Stack() g=Graph() i=0 finishingTime=0 l={} g1=Graph() q=Queue() temp=[] def myDfs(currentVertex): currentVertex.setColor("gray") for vertex in currentVertex.getConnections(): if vertex.getColor()=="white": myDfs(vertex) currentVertex.setColor("black") print currentVertex.getId() temp.append(currentVertex.getId()) return temp def Dfs(vertex): print "passed vertex",vertex.getId() stk.push(vertex) while stk.isEmpty()==False: currentVertex=stk.pop() global finishingTime currentVertex.setColor("gray") for vertex in currentVertex.getConnections():
vertex.setDistance(sys.maxsize) vertex.setPred(None) startVertex.setDistance(0) pq.buildHeap([(v.getDistance(), v) for v in Graph]) while not pq.isEmpty(): currentVertex = pq.delMin() for vertex in currentVertex.getConnections(): newCost = currentVertex.getDistance() + currentVertex.getWeight( vertex) if newCost < vertex.getDistance(): vertex.setDistance(newCost) vertex.setPred(currentVertex) pq.decreaseKey(vertex, newCost) G = Graph() G.addEdge("u", "v", 2) G.addEdge("v", "u", 2) G.addEdge("v", "w", 3) G.addEdge("w", "v", 3) G.addEdge("u", "w", 5) G.addEdge("w", "u", 5) G.addEdge("u", "x", 1) G.addEdge("x", "u", 1) G.addEdge("x", "v", 2) G.addEdge("v", "x", 2) G.addEdge("x", "v", 2) G.addEdge("x", "w", 3) G.addEdge("w", "x", 3) ''' G.addEdge("x","y",1)
from pythonds.graphs import Graph from pythonds.basic import Queue queue=Queue() graph=Graph(); start=graph.addVertex("0,0") def extractQuantity(quantities): quants=quantities.split(",") return [int(quants[0]),int(quants[1])] def makeVertex(list): newList=[str(list[0]),str(list[1])] return ",".join(newList) def findPossibleChildrens(vertex,q1,q2): childrens=[] quantities=extractQuantity(vertex.getId()) quant1=quantities[0] quant2=quantities[1] # first quantity to river if not quant1==0: childrens.append(makeVertex([0,quant2])) if not quant2==q2: canHold=q2-quant2 if(canHold>=quant1): temp2=quant2+quant1 temp1=0 else: temp2=canHold temp1=abs(canHold-quant1) childrens.append(makeVertex([temp1,temp2]))