Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a recursive function depthC\'ount() that takes an arbitrarily nested list

ID: 3840375 • Letter: W

Question

Write a recursive function depthC'ount() that takes an arbitrarily nested list as a parameter and returns the maximum depth to which the List has nested sublists. For example, a list with no sublists would have depth (). A list with a sublist that contains no sublists itself would have depth 1. Even' time a sublist of the list has a sub list itself, the depth increases by 1. There are several examples provided below for your reference. You are not allowed to use any list methods in your function other than indexing (e.g. 1st[i] for some integer i). slicing (1st[i:j] for some integers i and j), or 1en(). Remember that you can test whether an item is a list by writing: if type(item) - list. In writing the function you should not use any loops You may assume that the initial value given to the function is a list, and your function does not have to behave in any reasonable way when given something other than a list as a parameter. The following shows the behavior of the function on some sample parameters. Please remember that these examples are just that. Your function must work correctly on all valid parameters, and you may not make any assumptions about the number of nested sublists or the depth of the nesting in the list provided as a parameter to the function. >>> depthCount ([]) 0 >>> depthCount ([1, 2, 3]) 0 >>> depthCount ([1], [2, 3]) 1 >>> depthCount ([[[1]], [2, 3]]) 2 >>> depthCount ([[1], [[2, 3]]) 2 >>> depthCount ([1, [[[[2], 3]], [[[[[[[[4]]]]]]]]]]) 9 >>>

Explanation / Answer


def depthCount(x, depth=0):
if not x or type(x) != list:
return depth
return max(depthCount(x[0], depth+1),
depthCount(x[1:], depth))

print depthCount([1, [2,3], [4, [5]]])
print depthCount([[[1], 'a', [-5.5]], [(6,3)], [['hi']]])
print depthCount([1, [2,3], [[[[[[[[[[4]]]]]]]]]]])

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote