Counting depth or the deepest level a nested list goes to

前端 未结 13 1713
無奈伤痛
無奈伤痛 2020-12-02 21:04

A have a real problem (and a headache) with an assignment...

I\'m in an introductory programming class, and I have to write a function that, given a list, will retur

相关标签:
13条回答
  • 2020-12-02 21:34

    Here is one way to write the function

    depth = lambda L: isinstance(L, list) and max(map(depth, L))+1
    

    I think the idea you are missing is to use max()

    0 讨论(0)
  • 2020-12-02 21:35

    @John's solution is excellent, but to address the empty list cases, like [], [[]], you may need to do something like this

    depth = lambda L: isinstance(L, list) and (max(map(depth, L)) + 1) if L else 1

    0 讨论(0)
  • 2020-12-02 21:38

    Did it in one line of python :)

    enjoy

    def f(g,count=0): return count if not isinstance(g,list) else max([f(x,count+1) for x in g])
    
    0 讨论(0)
  • 2020-12-02 21:39

    Breadth-first, without recursion, and it also works with other sequence types:

    from collections import Sequence
    from itertools import chain, count
    
    def depth(seq):
        for level in count():
            if not seq:
                return level
            seq = list(chain.from_iterable(s for s in seq if isinstance(s, Sequence)))
    

    The same idea, but with much less memory consumption:

    from collections import Sequence
    from itertools import chain, count
    
    def depth(seq):
        seq = iter(seq)
        try:
            for level in count():
                seq = chain([next(seq)], seq)
                seq = chain.from_iterable(s for s in seq if isinstance(s, Sequence))
        except StopIteration:
            return level
    
    0 讨论(0)
  • 2020-12-02 21:39

    you can also do it recursively using only python :

    def depth(L,d):
        max = d
        for i in range(len(L)):
            if type(L[i])==list :
                a = depth(L[i],d+1)
                if a>max :
                     max = a
        return(max)
    

    this function is recursive and what it does is that it just goes to the maximum depth of your list counting how deep the list is, and when it climbs back up, it keeps only the biggest deepness registered among all nested lists.

    0 讨论(0)
  • A way that does not need any additional modules and has the same speed, no matter what depth:

    def depth(nested):
        instring = False
        count = 0
        depthlist = []
        for char in repr(nested):
            if char == '"' or char == "'":
                instring = not instring
            elif not instring and ( char == "[" or char == ")" ):
                count += 1
            elif not instring and ( char == "]" or char == ")" ):
                count -= 1
            depthlist.append(count)
        return(max(depthlist))
    

    Basically, what this does is convert the list to a string using repr(). Then for every character in this string equal to "(" or "[" it increases the variable count. for the closing brackets it decreases count. It then returns the maximum that count has reached.

    0 讨论(0)
提交回复
热议问题