Friday, 13 September 2013

variable scope and recrusion in python

variable scope and recrusion in python

Can you please tell me why the parent-child relationship needs to be
appended inside the for loop to get the expected output. I am not
understanding scope 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]]

No comments:

Post a Comment