0
def recursive_min(nestedlist):
    first = nestedlist[0] 
    min_list = [first]
    for i in range(len(nestedlist)):
        if type(nestedlist[i]) == list:
            recursive_min(nestedlist[i])
    for i in range(len(nestedlist)):
        if nestedlist[i] < min_list[0]:
            min_list[0]= nestedlist[i]
    return min_list
    
nestedlist = [3, 5, 3, 5, 2, -5, 0, 5, -22, [3, 1, 5, 3]]
    
print(recursive_min(nestedlist))

I am trying to write a function with recursion that returns the smallest value in a nested number list. There won't be any empty lists or sublists

Can anyone help with this problem?

Thanks in advance!

Peter Wu
  • 3
  • 2
  • You aren't doing anything with the return value of the recursive call. – chepner Mar 15 '23 at 18:48
  • 1
    I would take a look at [this way of flatten nested lists](https://stackoverflow.com/a/73928597). As you can use it as an iterable, you can pass it to the built in [`min`](https://docs.python.org/3/library/functions.html#min) function. – Jorge Luis Mar 15 '23 at 18:53
  • Shouldn't this return a *number* as opposed to a list? – Scott Hunter Mar 15 '23 at 18:56

1 Answers1

0

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

BeXXsoR
  • 91
  • 2