Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counting depth or the deepest level a nested list goes to

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 return the "maximum" depth 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...

like image 624
dhcarmona Avatar asked May 18 '11 02:05

dhcarmona


People also ask

How to count the number of lists in a nested list Python?

Use List comprehension to count elements in list of lists. Iterate over the list of lists using List comprehension. Build a new list of sizes of internal lists. Then pass the list to sum() to get total number of elements in list of lists i.e.

How to count number of list in Python?

There is a built-in function called len() for getting the total number of items in a list, tuple, arrays, dictionary, etc. The len() method takes an argument where you may provide a list and it returns the length of the given list.

How deep is a Python?

Python uses a maximum recursion depth of 1000 to ensure no stack overflow errors and infinite recursions are possible. This recursion limit is somewhat conservative, but it is reasonable as stack frames can become big in Python.


1 Answers

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()

like image 153
John La Rooy Avatar answered Oct 07 '22 06:10

John La Rooy