0

I have the following dictionaries:

{} depth: 0  
{"x":5} depth: 1  
{"x":5,"y":[1,2,3]} depth: 2  
{"x":5,"y":{"a":2,"b":67}} depth: 2  
{ "x" : 5,"y" : [ [ 1 , 2 ] , [ 3 , 4 ] ]} depth: 3 

I searched in the internet and I fount several ways to get the depth of the aboves but no one return 3 for the last one. Finally, is it correct the Depth = 3 for the last one or not, and how I can get it.
Thanks
Elias

ekekakos
  • 563
  • 3
  • 20
  • 39
  • 3
    how is the second dictionary's depth 2? it's just one dictionary. In the same way, the last one is 1. Just count the number of pairs of opening and closing curly braces – Tharun K Feb 25 '21 at 07:34

1 Answers1

2

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
alexzander
  • 1,586
  • 1
  • 9
  • 21