这是一个创建于 4087 天前的主题,其中的信息可能已经有所发展或是发生改变。
env :
Python 2.7.2 (default, Oct 11 2012, 20:14:37)
[GCC 4.2.1 Compatible Apple Clang 4.0 (tags/Apple/clang-418.0.60)] on darwin
问题,copyedNode.neighbors.append(copyingNode)这一行会把copyingNode的neighbors同样append一个copyingNode自身,不懂求指教
class Node():
index = 0
neighbors = []
def __init__ (self, arg) :
self.index = arg
def description(self):
out = []
out.append (self.index)
for item in self.neighbors:
out.append(item.index)
print (out)
def allNode (self, checkArray, out) :
tempNodesArray = self.neighbors[:]
tempNodesArray.append(self)
for node in tempNodesArray:
if node in checkArray:
pass
else:
checkArray.append(node)
if node in out:
pass
else:
out.append(node)
node.allNode(checkArray, out)
def copy(self):
queue = [self]
copyNode = Node(self.index)
nodesMap = {self:copyNode}
while len(queue) > 0:
node = queue.pop()
copyedNode = nodesMap[node]
for subNode in node.neighbors :
if subNode in nodesMap :
copyedNode.neighbors.append(nodesMap[subNode])
else:
copyingNode = Node(subNode.index)
copyedNode.neighbors.append(copyingNode)
copyingNode.neighbors = []
nodesMap[subNode] = copyingNode
queue.append(subNode)
copyedNode.description()
return copyNode
#///////// test code below //////////
#create nodes in graph
nodes = []
for i in range (0, 7) :
node = Node(i)
nodes.append(node)
#create relation ships among all nodes
for node in nodes:
tempNodesArray = nodes[:]
tempNodesArray.remove(node)
node.neighbors = tempNodesArray
print("old graph")
for node in nodes:
node.description()
print("new graph")
newnode = nodes[0].copy()
3 条回复 • 1970-01-01 08:00:00 +08:00
|
|
1
TankyWoo 2013-09-20 02:41:27 +08:00
用 gist 重贴一下你的代码吧。
Python代码没有格式,缩进会要人命的。。。
|
|
|
2
Karsa 2013-09-22 17:14:40 +08:00
|
|
|
3
Karsa 2013-09-22 17:18:00 +08:00
唉,第一次在这里使用gist,想着把嵌入代码放上,加个链接的,结果变成这样了。囧~~~
|