The second recursion question. I need to assign unique ID’s to values in a recursive function.
Think of a folder structure, where each folder can have items or other folders. But each of those need a unique ‘id’.
I figured, since I can’t use any global variables in my recursive functions in python, that I’d increment the id with each call. But I couldn’t be more wrong. Think of the following situation.
1 – Folder
2- Folder
3 – Item
4 – Item
2 – Folder
Because of the way the recursion works, the id gets assigned twice, and there’d be no way to check. How would I go and do this? (I’m using python. Whenever I have a variable ‘uniqueid’ that I increment I get the error:
local variable ‘uniqueid’ referenced before assignment
)
My code: make_link_item just returns a string.
def build_xml(node,depth,itemid):
#if 'Children' in node:
#print colleges
depth += 1
for child in node['Children']:
itemid += 1
print (" " * (depth - 1)) + "<item identifier=\"%s\" identifierref=\"%s\">" % (("itm" + ("%05d" % itemid)),("res" + ("%05d" % itemid)))
print (" " * depth) + "<title>%s</title>" % child['Name'].encode('utf-8')
build_xml(child,depth,itemid)
print (" " * (depth - 1)) + "</item>"
lectures = getlectures(node['Id'])
if lectures:
build_lectures(lectures,itemid,itemid)
def build_lectures(lectures,itemid,parentid):
for x in range(len(lectures)):
itemid += 1
if x % 2 == 0:
print "<item identifier=\"%s\" identifierref=\"%s\">" % (("itm" + ("%05d" % itemid)),("res" + ("%05d" % itemid)))
print "<title>" + lectures[x].encode('utf-8') + "</title>"
print "</item>"
else:
make_link_item(lectures[x-1].encode('utf-8'),lectures[x].encode('utf-8'),itemid,parentid)
Thanks,
Mats
I hope I don’t miss the question.
You could go with a
class Builderthat is the object for building xml arborescence. Your class has got a memberincrement, which you increment by one each time you meet a new item. This way, there are no two same IDs.