I am working through How to Think Like a Computer Scientist, and am currently trying to get a grasp on recursion. I am having trouble on one of the problems, so I am hoping you can help me out.
I am writing a function which finds the recursive minimum of a list, whose elements are integers, lists of integers, lists of lists of integers, etc.
Here is my current version:
def recursive_min(nested_num_list):
"""
>>> recursive_min([9, [1, 13], 2, 8, 6])
1
>>> recursive_min([2, [[100, 1], 90], [10, 13], 8, 6])
1
>>> recursive_min([2, [[13, -7], 90], [1, 100], 8, 6])
-7
>>> recursive_min([[[-13, 7], 90], 2, [1, 100], 8, 6])
-13
"""
min = nested_num_list[0]
while type(min) == type([]):
min = min[0]
for item in nested_num_list:
if type(item) == type([]):
recursive_min(item)
elif item < min:
min = item
return min
However, this only works to find the minimum at the top level, so I now my code is not getting in to the depth of the list.
Now, looking at the answers, I know my version should read something like:
def recursive_min(nested_num_list):
"""
>>> recursive_min([9, [1, 13], 2, 8, 6])
1
>>> recursive_min([2, [[100, 1], 90], [10, 13], 8, 6])
1
>>> recursive_min([2, [[13, -7], 90], [1, 100], 8, 6])
-7
>>> recursive_min([[[-13, 7], 90], 2, [1, 100], 8, 6])
-13
"""
min = nested_num_list[0]
while type(min) == type([]):
min = min[0]
for item in nested_num_list:
if type(item) == type([]):
min_of_elm = recursive_min(item)
if min_of_elm < min:
min = min_of_elm
elif item < min:
min = item
return min
Notice that instead of just executing recursive_min(item), it assigns it to a variable, and compares it to the current min. I don’t see why I need to do that, as in my mind, if I execute the entire function over the embedded list, and that is a list of integers, it should then get to the elif statement (rather than the if statement) and properly compare the values.
I know I must be missing something here about recursion. I would really appreciate any insight you might be able to give me to help me understand what makes the second version work but the first version fail.
Thank you!
Why would it work? You call the function, and it recurses until it finds the min. Then what does it do? It exits back out of all the recursions in turn, until it gets back to the top level. At that point, what’s the value of
min? Exactly what it was before you started recursing, because you never captured the return value from the recursive function.Don’t forget that each call of the function has its own local variables, therefore its own local value of
min.