Counting depth or the deepest level a nested list goes to

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

    Abusive way: Say your list is called mylist
    mybrackets = map(lambda x: 1 if x=='[' else -1, [x for x in str(mylist) if x=='[' or x==']'])
    maxdepth = max([sum(mybrackets[:i+1]) for i in range(len(mybrackets))])

    This converts your list to a list of opening and closing brackets, then finds the largest number of opening brackets that occur before the corresponding closing bracket occurs.

提交回复
热议问题