你能告诉我为什么需要在 for 循环中附加父子关系以获得预期的输出。我不了解 Python 中的范围。
#a unique id to be given to each node
current_id = 0
#ids = [parent_id, current_id]; stores parent_child tree data
ids = []
#MWE of depth first search
def bt(parent_id):
global ids
global current_id
#increament current id because we just created a new node
current_id = current_id +1
#store the parent to child relationship in the list called ids
ids.append([parent_id,current_id])
#show the parent child relationship that is getting append to the ids list
print 'parent-child (outside loop)', [parent_id,current_id]
if(parent_id) > 1:
return
for i in range(2):
print 'parent-child (inside loop)', [parent_id,current_id]
bt(current_id)
#run depth first search
print bt(0)
#print list of parent to child relationships
print 'list of parent-child relationships\n',ids
print 'expected output',[[0,1],[1,2],[1,3],[0,4]]
编辑:这个脚本的输出是:
parent-child (outside loop) [0, 1]
parent-child (inside loop) [0, 1]
parent-child (outside loop) [1, 2]
parent-child (inside loop) [1, 2]
parent-child (outside loop) [2, 3]
parent-child (inside loop) [1, 3]
parent-child (outside loop) [3, 4]
parent-child (inside loop) [0, 4]
parent-child (outside loop) [4, 5]
None
list of parent-child relationships
[[0, 1], [1, 2], [2, 3], [3, 4], [4, 5]]
expected output [[0, 1], [1, 2], [1, 3], [0, 4]]