Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Clear category for How Deep by Red_Ale
def how_deep(structure):
# solved with recursion. First check find if there are nested item to start recursion.
def test(L, deep=1):
if type(L) == x:
for i in L:
if type(i) == type(L):
deep += test(i, deep)
return deep
return deep + 1
else:
return deep
# Check is done on the type of input data, this solution can be used on different iterators
x = type(structure)
element_depth = [test(i) for i in structure]
return max(element_depth) if len(element_depth) > 0 else 1
if __name__ == '__main__':
print("Example:")
print(how_deep((1, 2, 3)))
# These "asserts" are used for self-checking and not for an auto-testing
assert how_deep((1, 2, 3)) == 1
assert how_deep((1, 2, (3,))) == 2
assert how_deep((1, 2, (3, (4,)))) == 3
assert how_deep(()) == 1
assert how_deep(((),)) == 2
assert how_deep((((),),)) == 3
assert how_deep((1, (2,), (3,))) == 2
assert how_deep((1, ((),), (3,))) == 3
print("Coding complete? Click 'Check' to earn cool rewards!")
Feb. 27, 2022
Comments: