gpt4 book ai didi

python - 在递归函数中保持计数

转载 作者:太空宇宙 更新时间:2023-11-03 19:06:17 24 4
gpt4 key购买 nike

第二个递归问题。我需要为递归函数中的值分配唯一的 ID。

考虑一个文件夹结构,其中每个文件夹可以包含项目或其他文件夹。但其中每一个都需要一个唯一的“id”。

我想,因为我不能在 python 的递归函数中使用任何全局变量,所以我会在每次调用时增加 id 。但我大错特错了。考虑以下情况。

1 - Folder

2- Folder

3 - Item

4 - Item

2 - 文件夹

由于递归的工作方式,id 被分配了两次,并且无法检查。我该怎么做呢? (我正在使用 python。每当我增加一个变量“uniqueid”时,我都会收到错误:

local variable 'uniqueid' referenced before assignment

)我的代码: make_link_item 仅返回一个字符串。

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)

谢谢

垫子

最佳答案

我希望我不会错过这个问题。

您可以使用一个class Builder,它是用于构建 xml 树状结构的对象。您的类(class)有一个成员increment,每次遇到新项目时您都会将其增加一。这样就不会出现两个相同的ID。

class Builder:

def __init__(self):
self.increment = 0

#other methods you need

关于python - 在递归函数中保持计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14635150/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com