testcases:
testcases = [
{}, # 0
{"x":5}, # 1
{"x":5,"y":[1,2,3]}, # 2
{"x":5,"y":{"a":2,"b":67}}, # 2
{ "x" : 5,"y" : [ [ 1 , 2 ] , [ 3 , 4 ] ]} # 3
]
here is a quick solution:
level = 1
def calculate_depth(collection):
global level
if len(collection) == 0:
return 0
else:
if isinstance(collection, dict):
for item in collection.values():
if isinstance(item, list) or isinstance(item, dict):
level += 1
calculate_depth(item)
break
elif isinstance(collection, list):
for item in collection:
if isinstance(item, list) or isinstance(item, dict):
level += 1
calculate_depth(item)
break
return level
# testing
for t in testcases:
d = calculate_depth(t)
print(d)
level = 1
output
0
1
2
2
3
i dont like the global variable level
so, there is the solution without global variable:
def calculate_depth(coll):
if isinstance(coll, dict):
if coll == {}:
return 0
else:
return 1 + (max(map(calculate_depth, coll.values())))
elif isinstance(coll, list):
if coll == []:
return 0
else:
return 1 + (max(map(calculate_depth, coll)))
return 0
# testing
for t in testcases:
d = calculate_depth(t)
print(d)
output
0
1
2
2
3