通过递归列出深度查找时出现全局变量问题



我有一个递归函数,它带有一个全局变量,用于检查列表深度,它可以正常工作,直到您启动它两次或多次,因为变量不会重置。我已经看到了最简单的方法,但我能修复我的代码以获得正确的工作吗?还是它只是一段死代码?哦,我真的有递归的问题。。

depth = 1
def list_depth(arr):
global depth
for element in arr:
# print(type(element))
if type(element) == list:
depth += 1
list_depth(element)
else:
continue
return depth
return depth
print(list_depth([1, [2, [3, [4, [5, [6], 5], 4], 3], 2], 1])) # => 6 correct
print(list_depth([1, [2, [3, [4, [5, [6], 5], 4], 3], 2], 1])) # => 11 wrong

有几种方法可以实现。。。如果你真的想保持代码的原样,你必须在每次调用前重置depth像这样:

print(list_depth([1, [2, [3, [4, [5, [6], 5], 4], 3], 2], 1]))
depth=1
print(list_depth([1, [2, [3, [4, [5, [6], 5], 4], 3], 2], 1]))

输出:

6
6

但更好的解决方案可能是将深度作为函数参数之一发送,而不是将其声明为全局参数

这应该能奏效:

def list_depth(arr,depth=1):
for element in arr:
# print(type(element))
if type(element) == list:
depth += 1
return list_depth(element,depth)
else:
continue
return depth
print(list_depth([1, [2, [3, [4, [5, [6], 5], 4], 3], 2], 1])) 
print(list_depth([1, [2, [3, [4, [5, [6], 5], 4], 3], 2], 1]))

输出:

6
6

最新更新