There are a few issues with your code:
- The main cause why your code isn't working as expected is that the return value of the recursive call of your function isn't used anywhere, but you need to compare it to the minimal value that you've found so far, just as you do with regular numbers.
- The return value
min_list
is a list (because you initialized it with min_list = [first]
), which is unnecessary here, you can just use it as a number.
- You can simplify your for loops: instead of looping over the indexes and accessing the list items that way, you can directly loop over the items, and additionally you can skip the second loop and get all the desired functionality in one loop.
Try this code:
def recursive_min(nestedlist):
first = nestedlist[0]
min_list = first
for item in nestedlist:
if type(item) == list:
cur_value = recursive_min(item)
else:
cur_value = item
if cur_value < min_list:
min_list = cur_value
return min_list
nestedlist = [3, 5, 3, 5, 2, -5, 0, 5, -22, [3, 1, 5, 3]]
print(recursive_min(nestedlist)) # output: -22
# Second test case with more nested lists:
nestedlist2 = [3, 5, 3, 5, 2, -5, 0, 5, -22, [3, 1, 5, [3, -25]]]
print(recursive_min(nestedlist2)) # output: -25
By the way:
You can simplify that code a bit more: instead of
if type(item) == list:
cur_value = recursive_min(item)
else:
cur_value = item
you can simply write cur_value = recursive_min(item) if type(item) == list else item