Write a recursive function depthCount () that takes an arbitrarily nested list a
ID: 3672850 • Letter: W
Question
Write a recursive function depthCount() 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 0. A list with a sublist that contains no sublists itself would have depth 1. Every time a sublist of the list has a sublist 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. lst[i] for some integer i), slicing (lst[i:j] for some integers i and j), or len(). 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.
Python 3.4.1 Shell Eile Edit Shell Debug Options Windows Help depthCount () 0 >>>depthCount (1, 2, 3]) 0 >>>depthcount (1, 12, 311) >>>depthCount ( [2, 311) 2 >> depthcount ([1], 2, 3]]) >>> depthcount (, 2, 311) >>> depthCount (1, lll[21, 3, cccCCt41) 9 Ln: 39 Col:4Explanation / Answer
-------------------------------------------------------------------------------------------------------------------------------------------------
If they are just nested lists, e.g., [[[], []], [], [[]]], here's a nice solution:
Here's a slight variation you could use if you don't use Python 3.4, where the default argument was introduced:
They also differ by how they count. The first considers the empty list to be depth 1, the second to be depth 0. The first one is easy to adapt, though, just make the default -1.
If they're not just nested lists, e.g., [[[1], 'a', [-5.5]], [(6,3)], [['hi']]]), here are adaptions to that:
Make sure you understand how the latter one works. If you don't know it yet, it'll teach you how and works in Python :-)
Taking the "purely recursive" challenge:
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.