我从边缘列表构造节点邻居的 Python 代码怎么会出错?
我正在处理树,并且编写了一些简单的代码来将表示为节点编号对的边列表转换为邻居数组,其中第 i 个元素应该是节点 i 的相邻节点的列表。代码是:
def calculateNeighbors( n, edges ):
neighbors = [[]] * n
for edge in edges:
v1 = edge[ 0 ]
v2 = edge[ 1 ]
neighbors[ v1 ].append( v2 )
neighbors[ v2 ].append( v1 )
return neighbors
当我运行 n
=4
和 edges
=[[1,0],[1,2 ],[1,3]]
,我得到以下结果:
[[0, 1, 2, 1, 3, 1], [0, 1, 2, 1, 3, 1], [0, 1, 2, 1, 3, 1], [0, 1, 2, 1, 3, 1]]
看起来像边缘列表的四个副本。有人请指出我哪里出错了吗?我期望结果是这样的 [[1],[0,2,3],[1],[1]]
I am working with trees and I've written some simple code to convert a list of edges, expressed as node number pairs, to a neighbors array where with i-th element is supposed to be a list of node i's neighboring nodes. The code is:
def calculateNeighbors( n, edges ):
neighbors = [[]] * n
for edge in edges:
v1 = edge[ 0 ]
v2 = edge[ 1 ]
neighbors[ v1 ].append( v2 )
neighbors[ v2 ].append( v1 )
return neighbors
When I run this for n
=4
and edges
=[[1,0],[1,2],[1,3]]
, I get the following result:
[[0, 1, 2, 1, 3, 1], [0, 1, 2, 1, 3, 1], [0, 1, 2, 1, 3, 1], [0, 1, 2, 1, 3, 1]]
which looks like four copies of the edge list. Can someone please point out where I'm going wrong? I expected the result to be something like[[1],[0,2,3],[1],[1]]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我看到了问题所在。我初始化“邻居”的方式,四个子列表是同一个对象。打赌说
I see the problem. The way I'm initializing "neighbors", the four sublists are the same object. Betting to say