Counting depth or the deepest level a nested list goes to

前端 未结 13 1723
無奈伤痛
無奈伤痛 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: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
    

提交回复
热议问题