Example #1
0
def build_graph(word_file):
    d = {}
    g = Graph()

    wfile = open(word_file, '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]

    for word in d.keys():
        print(word, ':', d[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 word2 != word1:
                    g.addEdge(word1, word2)

    return g
def buildGraph(keys,length):
    d = {}
    g = Graph()
   
    #wfile = open(wordFile,'r')
    # create buckets of words that differ by one letter
    for k in keys:
        if(k.find('-') ==-1 and len(k) == length):      
            #word = k[:-1]
            word = k
            #print word          
            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 p in d['WEA_']:  Prints bucket 
    #    print p
    # 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 build_graph_with_word_file(word_file):
    """
    This
    :param word_file:
    :return: graph Object
    """
    d = {}
    g = Graph()
    wfile = open(word_file, '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, randint(0, 9))
                    # g.addEdge(word2, word1, randint(0, 9))
    # print(d)
    return g
Example #4
0
def buildGraph(filename):
    payG = Graph()

    for users in genUser(filename):
        payG.addEdge(users[0], users[1])

    return payG
Example #5
0
def buildGraph():
    d = {}
    g = Graph()
    word_list = ["fool", "pool", "poll", "pole", "pale", "page", "sage"]
    # 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]
    print(d)
    print(len(d))
    s = 0
    for i in d.values():
        s += len(i)
    print(s)
    # 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
Example #6
0
 def transpose(self, startVertex):
     g = Graph()
     for nextVertex in startVertex.getConnections():
         if nextVertex.getColor() == 'white':
             g.addEdge(nextVertex, startVertex)
             nextVertex.setColor('gray')
         self.transpose(nextVertex)
     startVertex.setColor('black')
     return g
Example #7
0
def knightGraph(bds):
    g = Graph()
    for row in range(bds):
        for col in range(bds):
            hull = gennumb(row,col,bds)
            node1 = genLegalMoves(row,col,bds)
            for j in node1:
                g.addEdge(hull,j)
    return g
Example #8
0
def knightGraph(bdsize):
    ktgraph = Graph()
    for row in range(bdsize):
        for col in range(bdsize):
            nodeId = posTonodeId(row,col,bdsize)
            legalMovesID = genLegalMovesID(row,col,bdsize)
            for move in legalMovesID:
                ktgraph.addEdge(nodeId,move)
    return ktgraph
Example #9
0
def knightGraph(boardSize):
    graph = Graph()
    for row in range(boardSize):
        for col in range(boardSize):
            boardNodeId = row * boardSize + col
            newPosition = legalMoves(row, col, boardSize)
            for node in newPosition:
                newNodeId = node[0] * boardSize + node[1]
                graph.addEdge(boardNodeId, newNodeId)
    return graph
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)
    return ktGraph
Example #11
0
def buildGraph(bdsize):
    ktGraph = Graph()
    for row in range(bdsize):
        for col in range(bdsize):
            nodeId = getNodeId(row, col, bdsize)
            legalMoves = getLegalMoves(row, col, bdsize)
            for options in legalMoves:
                nid = getNodeId(options[0], options[1], bdsize)
                ktGraph.addEdge(nodeId, nid)
    return ktGraph
Example #12
0
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)
    return ktGraph
def knightpathgraph(bdsize):
    ktgraph = Graph()   #Empty Graph
    for row in range(bdsize+1):     #Iterating through rows and columns
        for col in range(bdsize+1):
            nodeID = convloctoNode(row,col,bdsize) #Converting the rows and cols position to a Node
            legalmov = genlegalmov(row,col,bdsize) #Calculating all the available moves of a knight

            for e in legalmov:                      #Iterating through all the available moves
                newid = convloctoNode(e[0],e[1],bdsize) #Converting the available move into a Node
                ktgraph.addEdge(nodeID,newid)           #Adding edge betwwen the current Node and the available Node
    return ktgraph                                  #Thus, a graph of moves is built
Example #14
0
def buildGraph(counts):
    d = {'miss': (3, 2, 1, 0), 'cann': (3, 2, 1, 0), 'boat': (1, 0)}
    g = Graph()
    counts = counts
    # add vertices and edges for carying counts on the initial beach
    for counts in d.keys():
        for state1 in d[counts]:
            for state2 in d[counts]:
                if state1 != state2:
                    g.addEdge(state1, state2)
    return g
Example #15
0
def knightGraph(bdDize):
    #makes one pass over the entire board, helper function
    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)
    return ktGraph
Example #16
0
def knightGraph(bdSize):
    """ create graph and all the vertices(spots on board) and edges(legal moves)"""
    g = Graph()

    for row in range(bdSize):
        for col in range(bdSize):
            # for each cell figure out its possible next moves and create edges
            pos = posToNodeId(row,col,bdSize)
            moves = genLegalMoves(row,col,bdSize)
            for move in moves:
                movePos = posToNodeId(move[0],move[1],bdSize)
                g.addEdge(pos,movePos)
    return g        
Example #17
0
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
Example #18
0
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
Example #19
0
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 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
Example #21
0
class adjGraphTests(unittest.TestCase):
    def setUp(self):
        self.tGraph = Graph()
        
    def testMakeGraph(self):
        with open("./tests/test.dat") as gFile:
            for line in gFile:
                fVertex, tVertex = line.split('|')
                fVertex = int(fVertex)
                tVertex = int(tVertex)
                self.tGraph.addEdge(fVertex,tVertex)
        
        for i in self.tGraph:
            adj = i.getConnections()
            for k in adj:
                print(i.getId(), k.getId())
Example #22
0
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
Example #23
0
def buildGraph(wordFile):
    d = defaultdict(list)
    g = Graph()
    wordList = open(wordFile,'r').read().strip().split(',')
    # create a hash table
    for word in wordList:
        for i in range(len(word)):
            bucket =  word[:i] + '_' + word[i+1:]
            d[bucket].append(word)

    # create a graph
    for bucket in d.keys():
        for word1 in d[bucket]:
            for word2 in d[bucket]:
                if word1 != word2:
                    g.addEdge(word1,word2)

    return g
Example #24
0
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
Example #26
0
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[:-1] + '_' + 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]:
            if word1 != word2:
                g.addEdge(word1,word2)
    return g
def buildGraph(wordlist):
    d = {}
    g = Graph()
    # create buckets of words that differ by one letter
    for line in wordlist:
        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)
    return g
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
Example #29
0
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')
    # create buckets of words that differ by one letter i个字母单词可以属于i个桶
    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 un 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
Example #31
0
def buildGraph(filename):
	""" Parses edge file and builds graph
	Args:
		filename (str): input file name of edges file -- "source_id target_id"
	Returns:
		graph: edges (int(source), int(target))
	"""
	g = Graph()
	widgets = ['Building graph: ', Percentage(), ' ', Bar()]
	output = subprocess.check_output(["wc", "-l", filename]).split(' ')
	num_lines = int(output[0])
	pbar = ProgressBar(widgets=widgets, maxval=num_lines).start()
	with open(filename, 'r') as f:
		for i in range(num_lines):
			line = f.readline()
			line = line.strip()
			line = line.split(" ")
			g.addEdge(int(line[SOURCE]), int(line[TARGET]))
			pbar.update(i+1)
		pbar.finish()
	return g
def buildGraph(wordDoc):
    d = {}
    g = Graph()
    wfile = open(wordFile, 'r')
    #create bucket of words that differ by one letter and add the word to the bucket.
    for line in wordFile:
        #Assuming word file has 1 word per line
        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]
    #Connect words in same bucket with edges.
    for bucket in d:
        for word1 in bucket:
            for word2 in 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(wordFile):
    d = {}
    g = Graph()
    wfile = open(wordFile, 'r')
    # create buckets of words that differ by one letter
    for line in wfile:
        # last line is EOF
        word = line[:-1]
        for i in range(len(word)):
            # replacing a character with '_' one by one
            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
Example #35
0
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
Example #36
0
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
Example #37
0
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
Example #38
0
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
Example #39
0
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")


#        5: [2],
#        6: [5],
#        7: [3, 6],
#        8: [4, 7] }

graph = {1: [2, 8],
        2: [1, 8, 3],
        3: [2, 4, 6, 9],
        4: [3, 5, 6],
        5: [4, 6],
        6: [3, 5, 7, 4],
        7: [6, 8, 9],
        8: [1, 2, 7, 9],
        9: [3, 7, 8]}

# 1. Create graph
graphl = Graph()

for k,v in graph.iteritems():
    graphl.addVertex(k)
    for i in v:
        graphl.addEdge(k, i)

# 2. Draw the graph
draw_graph(graph, len(edges) )

# 3. Run the algorithm
dfs(graphl)

pause(30)
Example #41
0
    for counter in range(len(maxLengths)):
        if le>maxLengths[counter]:
            maxLengths[counter]=le
            break
def connectedComponents():
    for i in range(finishingTime,0,-1):
        vertId=l[i]
        if g1.getVertex(vertId).getColor()!="black":
            global temp
            temp=[]
            val=myDfs(g1.getVertex(vertId))
            if len(val)>1 :
                processMaxLengths(len(val))


'''
g.addEdge(1,2)
g.addEdge(2,5)
g.addEdge(2,3)
g.addEdge(3,6)
g.addEdge(4,2)
g.addEdge(5,1)
g.addEdge(5,4)
g.addEdge(4,7)
g.addEdge(7,5)
g.addEdge(6,8)
g.addEdge(8,9)
g.addEdge(9,6)
'''
'''
g.addEdge(1,2)
Example #42
0
    while q.isEmpty()==False:
        vert=q.dequeue()
        currentVertex=g1.getVertex(vert.getId())

        if(currentVertex.getColor()!="black"):
            print "current",currentVertex.getId()
            global temp
            temp=[]
            val=myDfs(currentVertex)
            if len(val)>1 :
                processMaxLengths(len(val))




'''
g.addEdge(1,2)
g.addEdge(2,5)
g.addEdge(2,3)
g.addEdge(3,6)
g.addEdge(4,2)
g.addEdge(5,1)
g.addEdge(5,4)
g.addEdge(4,7)
g.addEdge(7,5)
g.addEdge(6,8)
g.addEdge(8,9)
g.addEdge(9,6)
'''

g.addEdge(1,2)
Example #43
0
    while not pq.isEmpty():
        currentVertex=pq.delMin()
        pred=currentVertex.getPred()
        if pred:
            print ("( %s ,%s , %d)" % (currentVertex.getId(),pred.getId(),currentVertex.getDistance()))
        print currentVertex.getId(),
        for vertex in currentVertex.getConnections():
            newCost=currentVertex.getWeight(vertex)
            if newCost<vertex.getDistance():
                vertex.setDistance(newCost)
                vertex.setPred(currentVertex)
                pq.decreaseKey(vertex,newCost)


G=Graph()
G.addEdge("a","b",2)
G.addEdge("b","a",2)
G.addEdge("a","c",3)
G.addEdge("c","a",3)
G.addEdge("b","c",1)
G.addEdge("c","b",1)
G.addEdge("b","d",1)
G.addEdge("d","b",1)
G.addEdge("b","e",4)
G.addEdge("e","b",4)
G.addEdge("d","e",1)
G.addEdge("e","d",1)
G.addEdge("c","f",5)
G.addEdge("f","c",5)
G.addEdge("e","f",1)
G.addEdge("f","e",1)
Example #44
0
    for vertex in Graph:
        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)
G.addEdge("y","x",1)
Example #45
0
from pythonds.graphs import Graph

def Dfs(currentVertex):
    currentVertex.setColor("gray")
    for vertex in currentVertex.getConnections():
        if vertex.getColor()=="white":
            Dfs(vertex)
    currentVertex.setColor("black")
    print currentVertex.getId()

g=Graph()
g.addEdge(0,1)
g.addEdge(0,3)
g.addEdge(1,2)
g.addEdge(1,3)
g.addEdge(3,4)
g.addEdge(4,5)
g.addEdge(4,1)
g.addEdge(5,2)

Dfs(g.getVertex(0))