dhcarmona - 1 year ago 62
Python Question

# Counting "deepness" or the deepest level a nested list goes to

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

I'm in an introductory programming class, and I have to write a function that, given a list, will return the "maximum" deepness it goes to...
For example: [1,2,3] will return 1, [1,[2,3]] will return 2...

I've written this piece of code (it's the best I could get T_T)

``````def flat(l):
count=0
for item in l:
if isinstance(item,list):
count+= flat(item)
return count+1
``````

However, It obviously doens't work like it should, because if there are lists that do not count for the maximum deepness, it still raises the counter...

For example: when I use the function with [1,2,[3,4],5,[6],7] it should return 2, but it returns 3...

Any ideas or help would be greatly appreciated ^^ thanks a lot!! I've been strugling with this for weeks now...

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
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download