本文整理汇总了Python中Graph.Graph.addEdge方法的典型用法代码示例。如果您正苦于以下问题:Python Graph.addEdge方法的具体用法?Python Graph.addEdge怎么用?Python Graph.addEdge使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Graph.Graph
的用法示例。
在下文中一共展示了Graph.addEdge方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: main
# 需要导入模块: from Graph import Graph [as 别名]
# 或者: from Graph.Graph import addEdge [as 别名]
def main():
rows = read_file()
orders = {}
for row in rows:
if row['Order__c'] not in orders:
orders[row['Order__c']] = []
orders[row['Order__c']].append({'Id': row['Id'], 'Shipper':row['Revenova_Shipper__c'],'Consignee':row['Revenova_Consignee__c'],'Carrier':row['Carrier__c']})
for name in orders:
try:
graph = Graph()
for load in orders[name]:
shipper = str(load['Shipper'])
consignee = str(load['Consignee'])
graph.addVertex(shipper,{'ship':load['Id']})
graph.addVertex(consignee,{'cons':load['Id']})
graph.addEdge(shipper, consignee, str(load['Carrier']))
custResults[name] = graph.flattenCustomerLoads()
carrResults[name] = graph.flattenCarrierLoads()
except RuntimeError:
errors.append(name)
print 'Recursion Error'
print 'Successes: '+str(len(orders))
print 'Errors: '+str(len(errors))
custLoads = [{'Order':n, 'Shipper':i['Shipper'], 'Consignee':i['Consignee']} for n in custResults for i in custResults[n]]
write_file(custLoads,'cust-loads.csv')
carrLoads = [{'Order':n, 'Shipper':i['Shipper'], 'Consignee':i['Consignee'], 'Carrier':i['Carrier']} for n in carrResults for i in carrResults[n]]
write_file(carrLoads,'carr-loads.csv')
示例2: addEdge
# 需要导入模块: from Graph import Graph [as 别名]
# 或者: from Graph.Graph import addEdge [as 别名]
def addEdge(u, v, weight):
Graph.addEdge(u, v);
queues[u].add(WeightedEdge(u, v, weight))
n = [u, v, weight]
self.edges.append([])
for i in n:
self.edges[len(self.edges) - 1].append(i)
示例3: GraphTest
# 需要导入模块: from Graph import Graph [as 别名]
# 或者: from Graph.Graph import addEdge [as 别名]
class GraphTest(unittest.TestCase):
graph = None
adj = None
mutex = 0
def setUp(self):
if self.mutex == 0:
self.graph = Graph([1,2,3,4,6])
self.graph.addEdge(1,3)
self.graph.addEdge(2,4)
self.graph.addEdge(2,6)
self.graph.addEdge(6,4)
self.adj = self.graph.getAdj()
self.mutex = 1
def tearDown(self):
self.graph = None
def testDegree (self):
assert self.graph.degree(1) == len(self.adj[0]), 'degree = x\n'
assert self.graph.degree(4) == len(self.adj[3]), 'degree = x\n'
def testMaxDegree(self):
assert self.graph.maxDegree() == len(self.adj[4]), 'max degree = x\n'
def testAvgDegree(self):
assert self.graph.avgDegree() == (sum(map(len,self.adj))/2), 'avg degree = \n'
def testSelfLoops(self):
#assert self.graph.selfLoops() == , 'self loops = %d' % self.graph.selfLoops()
return
示例4: testGraph
# 需要导入模块: from Graph import Graph [as 别名]
# 或者: from Graph.Graph import addEdge [as 别名]
class testGraph(unittest.TestCase):
def setUp(self):
self.graph = Graph()
# @unittest.skip("jeszcze nie mamb")
def testCreateSpecyficGraphFromFile(self):
readFromFileMock = mock.Mock(return_value = """
0 1 3\n
0 4 3\n
1 2 1\n
2 3 3\n
2 5 1\n
3 1 3\n
4 5 2\n
5 3 1\n
5 1 6""") #zakladanie werifikatora
readFromFileMock("testGraf.txt") #gen
readFromFileMock.assert_called_once_with("testGraf.txt") #sciaganie werifikatora
self.graph.createGraphFromStr(readFromFileMock.return_value)
self.assertEqual(6, self.graph.getNumberOfVertex())
self.assertEqual(9, self.graph.getNumberOfEdges())
# @unittest.skip("jeszcze nie mamb")
def testAddEdge(self):
s = [1, 2, 3]
self.graph.addEdge(s)
self.assertEqual([1], self.graph.getVertex())
self.assertEqual([[2]], self.graph.getConnectFromVertex(1))
self.assertEqual([3], self.graph.getEdgeFromVToVx(1, 2))
示例5: buildGraph
# 需要导入模块: from Graph import Graph [as 别名]
# 或者: from Graph.Graph import addEdge [as 别名]
def buildGraph(wordFile):
# algorithm connects words (vertices) by placing them in a bucket whose name is a (wildcard)+string of letters(n-1)...
# ... that way only one letter varies
bucketDictionary = {}
# create the graph
g = Graph()
fileObject = open(wordFile)
# create buckets of words that differ by a letter
for line in fileObject:
word = line[:-1] # strip off '\n' character
for index in range(len(word)):
# _ indicates the wildcard character
bucket = word[:index] + '_' + word[index+1:]
# check if bucket has already been created..
# yes..-> append the word to the correct bucket
if bucket in bucketDictionary:
bucketDictionary[bucket].append(word)
else:
bucketDictionary[bucket]= [word]
# connect words in a bucket by creating an edge between them
for bucket in bucketDictionary.keys():
for word1 in bucket:
for word2 in bucket:
# do not check for one way relationship because this is a non-directed graph
if word1 != word2:
# add edge method creates vertices if they do not already exist
g.addEdge(word1, word2, 0)
fileObject.close()
return g
示例6: parseGraphFromFile
# 需要导入模块: from Graph import Graph [as 别名]
# 或者: from Graph.Graph import addEdge [as 别名]
def parseGraphFromFile(fileName):
file = open(fileName, 'r')
line = file.readline()
graph = Graph()
# take out any extra whitespace, such as 1 $ 2 , 3...
line = re.sub("\s*", "", line)
# partition returns a 3-tuple of the string before the
# specified delimiter, the delimiter, and the string after
# the delimiter
parts = line.partition('$')
# the first part contains the list of nodes
# add each node to the graph
numNodes = parts[0]
for i in range(int(numNodes)):
graph.addNode()
# each edge has the form node1, node2, cost
edgeList = parts[2].split(';')
for edge in edgeList:
n1, n2, cost = edge.split(',')
n1 = int(n1)
n2 = int(n2)
cost = int(cost)
graph.addEdge(n1, n2, cost)
return graph
示例7: buildKnightTourGraph
# 需要导入模块: from Graph import Graph [as 别名]
# 或者: from Graph.Graph import addEdge [as 别名]
def buildKnightTourGraph(boardSize):
ktGraph = Graph()
for row in range(boardSize):
for column in range(boardSize):
nodeID = positionToNodeID(row, column, boardSize)
newPositions = generateLegalMoves(row, column, boardSize)
for moveVector in newPositions:
# create edges between current node and all it's possible move combinations
validMoveID = positionToNodeID(moveVector[0], moveVector[1], boardSize)
# creates the nodes for us
ktGraph.addEdge(nodeID, validMoveID, 0)
return ktGraph
示例8: prepG
# 需要导入模块: from Graph import Graph [as 别名]
# 或者: from Graph.Graph import addEdge [as 别名]
def prepG( type = 'class' ) :
if type == 'dict':
G = {1: [2,3,4,5],
2: [1,3,4,5],
3: [1,2,4],
4: [1,2,3,5,6,7],
5: [2,4],
6: [4],
7: [4, 5]
}
if type == 'class':
G = Graph()
for i in range(1,8):
G.addVertex(i)
G.addEdge(1, 2, 1)
G.addEdge(1, 3, 1)
G.addEdge(2, 3, 1)
for i in range(1,4) + range(5,8):
G.addEdge(4, i, 1)
G.addEdge(5, 2, 1)
G.addEdge(7, 5, 1)
if type == 'matrix':
G = [[0,1,1,1,0,0,0],
[1,0,1,1,1,0,0],
[1,1,0,1,0,0,0],
[1,1,1,0,1,1,1],
[0,1,0,1,0,0,0],
[0,0,0,4,0,0,0],
[0,0,0,1,1,0,0]]
return G
示例9: FortranDependencies
# 需要导入模块: from Graph import Graph [as 别名]
# 或者: from Graph.Graph import addEdge [as 别名]
class FortranDependencies ():
def __init__ (self, files):
from Graph import Graph
self.files = files
# The graph models the dependencies and is returned by this function
self.g = Graph()
self.__compute__()
def getDependencyGraph (self):
return self.g
def __compute__ (self):
from re import IGNORECASE, compile
# Mapping from a module name to its file name
moduleNameToFileName = {}
module_line_regex = compile("^\s*module\s+(\S+)\s*$", IGNORECASE)
program_line_regex = compile("^\s*program\s+(\S+)\s*$", IGNORECASE)
use_line_regex = compile("^\s*use", IGNORECASE)
for fileName in self.files:
self.g.addVertex(fileName)
f = open(fileName)
for line in f:
if module_line_regex.search(line) or program_line_regex.search(line):
lexemes = line.split()
moduleName = lexemes[len(lexemes) - 1]
moduleNameToFileName[moduleName] = fileName
print("Module '%s' in file '%s'" % (moduleName, fileName))
f.close()
for fileName in self.files:
f = open(fileName)
for line in f:
if use_line_regex.search(line):
lexemes = line.split()
moduleName = lexemes[len(lexemes) - 1]
if moduleName in moduleNameToFileName:
print("Adding edge %s to %s" % (moduleNameToFileName[moduleName], fileName))
self.g.addEdge(moduleNameToFileName[moduleName], fileName)
f.close()
示例10: visibility_graph
# 需要导入模块: from Graph import Graph [as 别名]
# 或者: from Graph.Graph import addEdge [as 别名]
def visibility_graph(S, start, goal):
V = getAllVertices(S)
V.append(start)
V.append(goal)
E = []
for v in V:
W = visible_vertices(v, S, start, goal)
for w in W:
E.append((v, w))
Gvis = Graph()
for v in V:
Gvis.addVertex(v)
for e in E:
Gvis.addEdge(e[0], e[1])
cost = GeoUtils.euclidean_distance(e[0],e[1])
Gvis.addCost((e[0], e[1]), cost)
return Gvis
示例11: GraphNet
# 需要导入模块: from Graph import Graph [as 别名]
# 或者: from Graph.Graph import addEdge [as 别名]
def GraphNet(M, N):
"""create an MxN net of nodes
Each node is connected to adjacent nodes in the cardinal directions.
Nodes are identified as tuples (m,n)
"""
G = Graph();
def in_bounds(m, n):
return 1 <= m <= M and 1 <= n <= N;
for m in range(1,M+1):
for n in range(1,N+1):
node = (m,n);
adjs = [(m-1,n), (m+1,n), (m, n-1), (m, n+1)];
adjs = filter(lambda (a, b): in_bounds(a, b), adjs);
for a in adjs:
G.addEdge((node, a));
return G;
示例12: buildGraph
# 需要导入模块: from Graph import Graph [as 别名]
# 或者: from Graph.Graph import addEdge [as 别名]
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]
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]
# 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
示例13: print
# 需要导入模块: from Graph import Graph [as 别名]
# 或者: from Graph.Graph import addEdge [as 别名]
print("Stack Test completed.")
print("-------------------------------------------------------")
print("This is the Graph Test: ")
graph = Graph()
graph.addVertex(1)
graph.addVertex(2)
graph.addVertex(3)
graph.addVertex(4)
graph.addVertex(5)
graph.addVertex(5)
graph.addVertex(6)
graph.addVertex(7)
graph.addVertex(8)
graph.addVertex(9)
graph.addVertex(10)
graph.addEdge(1,10)
graph.addEdge(1,2)
graph.addEdge(1,4)
graph.addEdge(1,6)
graph.addEdge(1,8)
graph.addEdge(11,10)
graph.addEdge(2,3)
graph.addEdge(2,5)
graph.addEdge(2,7)
graph.addEdge(2,9)
graph.addEdge(3,4)
graph.addEdge(4,6)
graph.addEdge(4,2)
graph.addEdge(4,9)
graph.addEdge(5,10)
graph.addEdge(5,3)
示例14: Graph
# 需要导入模块: from Graph import Graph [as 别名]
# 或者: from Graph.Graph import addEdge [as 别名]
if __name__ == "__main__":
g = Graph()
#add random vertices to the graph
for i in range(6):
g.addVertex(i)
#print all the newly added vertices
for vertex in g:
print vertex
#add edges between the vertices
g.addEdge(0,1,5)
g.addEdge(0,5,2)
g.addEdge(1,2,4)
g.addEdge(2,3,9)
g.addEdge(3,4,7)
g.addEdge(3,5,3)
g.addEdge(4,0,1)
g.addEdge(5,4,8)
g.addEdge(5,2,1)
#print all the edges of the graph
for v in g:
for w in v.getConnections():
print("( %s , %s )" % (v.getId(), w.getId()))
#print the BFS traversal of the graph
开发者ID:dxmahata,项目名称:elements-of-programming-interviews-python-solutions,代码行数:33,代码来源:GraphTraversals.py
示例15: Graph
# 需要导入模块: from Graph import Graph [as 别名]
# 或者: from Graph.Graph import addEdge [as 别名]
q.put(node)
return True
if __name__ == "__main__":
G1 = Graph()
G1.addVertex('a')
G1.addVertex('b')
G1.addVertex('c')
G1.addVertex('d')
G1.addVertex('e')
G1.addVertex('f')
G1.addEdge("a","b",1)
G1.addEdge("a","f",1)
G1.addEdge("f","e",1)
G1.addEdge("e","d",1)
G1.addEdge("d","c",1)
G1.addEdge("c","b",1)
print is_bipartite(G1,G1.getVertex('a'))
G2 = Graph()
G2.addVertex('a')
G2.addVertex('b')
G2.addVertex('c')
G2.addVertex('d')
G2.addVertex('e')
G2.addVertex('f')
开发者ID:dxmahata,项目名称:elements-of-programming-interviews-python-solutions,代码行数:33,代码来源:DetectingBipartiteGraphUsingBFS.py