Design a function depth_map which returns a dictionary whose keys are the depths of the items in and the value for a given key is a list of the items at that depth. The depth of an object in a nested list is the number of nested lists,enclosing the object. The depth of a single int is 0. If no items occur at a given depth, that key should not appear in the dictionary. Use function design recipe and you MUST USE RECURSION to solve the problem. this is my assignment and it's really confusing and I also can't find a way to solve it.
depth_map([19, [[22]], [-3, [8], 47]]) output ->{1: [19], 3: [22, 8], 2: [-3, 47]}
You need to use recursion. First create a function that checks the type. If the type is a list call the function again until it is not a list. Once that happens append the value to the list of whatever depth it is.
def depth_map(array: list, depth=1, result={}) -> dict:
for element in array:
if type(element) == list:
result = depth_map(element, depth + 1, result)
else:
if result.get(depth):
result[depth].append(element)
else:
result[depth] = [element]
return result
a = [19, [[22]], [-3, [8], 47]]
depth_map(a)