Не могли бы вы рассказать мне, почему отношения parent-child необходимо добавить в цикл for для получения ожидаемого результата. Я не понимаю область действия в Python.outvariable scope и recursion in 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]]
EDIT: Вывод этого сценария:
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]]
Что вы ожидаете от этого? Что происходит вместо этого? – BrenBarn
Ожидаемый результат выводится на последней строке: «Печать« ожидаемого выхода », ... [0,4]]». Результат, который я получаю, указан в строке выше: «print» list of parent -..., ids « – John
Это не имеет ничего общего с областью и все, что связано с строками' if (parent_id)> 1: return' , Причина, по которой «внешний цикл» и «внутренний цикл» отличается от третьей итерации, заключается не в том, что она находится внутри цикла, а когда родительский идентификатор достигает 1, он возвращается. –