-6

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]}

Yunnosch
  • 26,130
  • 9
  • 42
  • 54
  • Please provide enough code so others can better understand or reproduce the problem. – Community Oct 21 '22 at 22:37
  • 2
    nima kazemi, do not vandalize your posts. By posting on this site, you've irrevocably granted the Stack Exchange network the right to distribute that content under the [CC BY-SA 4.0 license](//creativecommons.org/licenses/by-sa/4.0/) for as long as it sees fit to do so. For alternatives to deletion, see: [I've thought better of my question; can I delete it?](https://.com/help/what-to-do-instead-of-deleting-question) – Ethan Oct 23 '22 at 17:12

1 Answers1

0

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)
Kushim
  • 303
  • 1
  • 7