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
I extended the hammar's answer for every iterable (strings disabled by default):
def depth(arg, exclude=None):
if exclude is None:
exclude = (str, )
if isinstance(arg, tuple(exclude)):
return 0
try:
if next(iter(arg)) is arg: # avoid infinite loops
return 1
except TypeError:
return 0
try:
depths_in = map(lambda x: depth(x, exclude), arg.values())
except AttributeError:
try:
depths_in = map(lambda x: depth(x, exclude), arg)
except TypeError:
return 0
try:
depth_in = max(depths_in)
except ValueError:
depth_in = 0
return 1 + depth_in
In Numpy, you can convert the data structure to a numpy array
and use its library functions. arr.shape
gives length per layer, so we can len()
the shape and get the depth of the structure:
import numpy as np
def f( lists )
arr = np.array( lists )
return len(arr.shape)
f( [[[1,2],[3,4]],[[3,4],[5,6]]] ) # results in 3
f( [[1,2],[3,4]] ) # results in 2
f( [1,2] ) # results in 1
f( [] ) # results in 1
Numpy docs for shape: https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.shape.html
Let's first rephrase your requirements slightly.
The depth of a list is one more than the maximum depth of its sub-lists.
Now, this can be translated directly to code:
def depth(l):
if isinstance(l, list):
return 1 + max(depth(item) for item in l)
else:
return 0
If you're looking for a quick fix
def getDepth(matrix):
try:
len(matrix)
return getDepth(matrix[0]) + 1
except:
return 0
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.
A short addition to what has been said so it can handle empty lists too:
def list_depth(list_of_lists):
if isinstance(list_of_lists, list):
if(len(list_of_lists) == 0):
depth = 1
else:
depth = 1 + max([list_depth(l) for l in list_of_lists])
else:
depth = 0
return depth