[英]python finding depth of a list using recursion
I need to find the depth of a list using recursion but and I can't use global variables or have more than one parameter.我需要使用递归找到列表的深度,但我不能使用全局变量或有多个参数。 this is the code that I have but I'm getting the error where I can't call depth because I cant use a global variable and when I call it inside the function when the recursion happens it just resets the variable
这是我拥有的代码,但出现了无法调用深度的错误,因为我无法使用全局变量,并且当我在 function 中调用它时,递归发生时它只是重置了变量
def how_deep(list_of_lists):
for i in list_of_lists:
if type(i) == list:
how_deep(i)
depth += 1
else:
print(depth)
if __name__ == '__main__':
print(how_deep([[[], [], [], [[[]]]], []],))
print(how_deep([]))
print(how_deep([[], []]))
print(how_deep([[[]], [], [[]], [[[]]]]))
print(how_deep([[[[], [[]], [[[]]], [[[[]]]]]]]))
print(how_deep([[[], []], [], [[], []]]))
As you loop through each item you want to record its maximum depth and return the maximum depth of an individual child in the list.当您遍历每个项目时,您要记录其最大深度并返回列表中单个子项的最大深度。 You could do something like this:
你可以这样做:
def how_deep(list_of_lists):
if not isinstance(list_of_lists, list):
return 0
return max(map(how_deep, list_of_lists), default=0) + 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.