【发布时间】:2018-06-05 15:26:34
【问题描述】:
有一个带有如下数字的图形结构。
在 python 的图形对象中加载这个结构。我把它做成了一个多行字符串,如下所示。
myString='''1
2 3
4 5 6
7 8 9 10
11 12 13 14 15'''
将其表示为列表列表。
>>> listofLists=[ list(map(int,elements.split())) for elements in myString.strip().split("\n")]
>>> print(listofLists)
[[1], [2, 3], [4, 5, 6], [7, 8, 9, 10], [11, 12, 13, 14, 15]]
在 python 中使用下面的节点和边类创建图形结构
节点类,它需要位置作为一个元组和一个值 示例:元素及其位置、值
1 --- position (0,0) and value is 1
2 --- position (1,0) and value is 2
3 --- position (1,1) and value is 3
节点类
class node(object):
def __init__(self,position,value):
'''
position : gives the position of the node wrt to the test string as a tuple
value : gives the value of the node
'''
self.value=value
self.position=position
def getPosition(self):
return self.position
def getvalue(self):
return self.value
def __str__(self):
return 'P:'+str(self.position)+' V:'+str(self.value)
edge 类在两个节点之间创建一条边。
class edge(object):
def __init__(self,src,dest):
'''src and dest are nodes'''
self.src = src
self.dest = dest
def getSource(self):
return self.src
def getDestination(self):
return self.dest
#return the destination nodes value as the weight
def getWeight(self):
return self.dest.getvalue()
def __str__(self):
return (self.src.getPosition(),)+'->'+(self.dest.getPosition(),)
有向图类如下。图结构构建为字典邻接列表。 {node1:[node2,node3],node2:[node3,node4]......}
class Diagraph(object):
'''the edges is a dict mapping node to a list of its destination'''
def __init__(self):
self.edges = {}
'''Adds the given node as a key to the dict named edges '''
def addNode(self,node):
if node in self.edges:
raise ValueError('Duplicate node')
else:
self.edges[node]=[]
'''addEdge accepts and edge class object checks if source and destination node are present in the graph '''
def addEdge(self,edge):
src = edge.getSource()
dest = edge.getDestination()
if not (src in self.edges and dest in self.edges):
raise ValueError('Node not in graph')
self.edges[src].append(dest)
'''getChildrenof returns all the children of the node'''
def getChildrenof(self,node):
return self.edges[node]
'''to check whether a node is present in the graph or not'''
def hasNode(self,node):
return node in self.edges
'''rootNode returns the root node i.e node at position (0,0)'''
def rootNode(self):
for keys in self.edges:
return keys if keys.getPosition()==(0,0) else 'No Root node for this graph'
一个创建和返回图形对象的函数。
def createmygraph(testString):
'''input is a multi-line string'''
#create a list of lists from the string
listofLists=[ list(map(int,elements.split())) for elements in testString.strip().split("\n")]
y = Diagraph()
nodeList = []
# create all the nodes and store it in a list nodeList
for i in range(len(listofLists)):
for j in range(len(listofLists)):
if i<=j:
mynode=node((j,i),listofLists[j][i])
nodeList.append(mynode)
y.addNode(mynode)
# create all the edges
for srcNode in nodeList:
# iterate through all the nodes again and form a logic add the edges
for destNode in nodeList:
#to add the immediate down node eg : add 7 (1,0) to 3 (0,0) , add 2 (2,0) to 7 (1,0)
if srcNode.getPosition()[0]==destNode.getPosition()[0]-1 and srcNode.getPosition()[1]==destNode.getPosition()[1]-1:
y.addEdge(edge(srcNode,destNode))
#to add the bottom right node eg :add 4 (1,1) to 3 (0,0)
if srcNode.getPosition()[0]==destNode.getPosition()[0]-1 and srcNode.getPosition()[1]==destNode.getPosition()[1]:
y.addEdge(edge(srcNode,destNode))
return y
如何列出两个节点之间所有可用的路径。特别是 1---->11 , 1---->12 , 1---->13 , 1---- >14 , 1---->15 对于这种情况,我尝试了左优先深度优先方法。但它无法获得路径。
def leftFirstDepthFirst(graph,start,end,path,valueSum):
#add input start node to the path
path=path+[start]
#add the value to the valueSum variable
valueSum+=start.getvalue()
print('Current Path ',printPath(path))
print('The sum is ',valueSum)
# return if start and end node matches.
if start==end:
print('returning as start and end have matched')
return path
#if there are no further destination nodes, move up a node in the path and remove the current element from the path list.
if not graph.getChildrenof(start):
path.pop()
valueSum=valueSum-start.getvalue()
return leftFirstDepthFirst(graph,graph.getChildrenof(path[-1])[1],end,path,valueSum)
else:
for aNode in graph.getChildrenof(start):
return leftFirstDepthFirst(graph,aNode,end,path,valueSum)
print('no further path to explore')
测试代码。
#creating a graph object with given string
y=createmygraph(myString)
函数返回终端节点,如 11、12、13、14、15。
def fetchTerminalNode(graph,position):
terminalNode=[]
for keys in graph.edges:
if not graph.edges[keys]:
terminalNode.append(keys)
return terminalNode[position]
运行深度优先左前函数。
source=y.rootNode() # element at position (0,0)
destination=fetchTerminalNode(y,1) #ie. number 12
print('Path from ',start ,'to ',destination)
xyz=leftFirstDepthFirst(y,source,destination,[],0)
为元素 11 和 12 获取路径,但不是为 13、14 或 15 获取路径。即 destination=fetchTerminalNode(y,2) 不起作用。请任何人提出解决此问题的方法。
【问题讨论】:
标签: python-3.x algorithm dictionary graph graph-algorithm