简体   繁体   中英

Recursive function to find the minimum value in a nested list, without using a for loop

I tried to do this to go through each list within the list.

def recMin(nestedLis, n=0) :
    if len(nestedLis) == 0 :
        return None
    elif len(nestedLis) == 1 :
        return nestedLis
    else :
        mini = recMin(nestedLis[n][1: ])
        smallest = nestedLis[i][0]
        if mini < smallest :
            smallest = mini
            mini = recMin(nestedLis[n + 1][1: ])
        return smallest

When I try an output like this:

print("Minimum: ", recMin([3, 5, 3, 5, [3, 1, 5, 3], [3, 2, 5]]))

It will return an error, however, I am trying to get it to print:

Minimum: 1

If you have a list of lists (as your question title suggests):

lst = [[3, 5, 3, 5], [3, 1, 5, 3], [3, 2, 5]]
min(min(lst, key=min))

If you have indeed an irregular list (as shown in your example) with int types and list types mixed:

import numpy as np
lst = [3, 5, 3, 5, [3, 1, 5, 3], [3, 2, 5]]
np.min([np.min(item) for item in lst])

Here's a code that works with nested lists (to whatever nesting level you want):

def recMin(nestedLis):
    if isinstance(nestedLis, int):
        return nestedLis
    if len(nestedLis) == 1:
        return recMin(nestedLis[0])
    if isinstance(nestedLis[0], list):
        return min(recMin(nestedLis[0]), recMin(nestedLis[1:]))
    if isinstance(nestedLis[0], int):
        return min(nestedLis[0], recMin(nestedLis[1:]))


print("Minimum: ", recMin([3, 5, 3, 5, [3, [1], [5, [932, -10], -1], 3], [3, 2, 5]]))

At no point in your code are you testing whether the elements on the list are themselves lists or not. In some form or other, you are going to have to do that, because how you then treat the elements will differ depending whether it is a number or a sublist. Below is an example implementation -- note the isinstance test.

def recMin(nestedLis):
    if len(nestedLis) == 0:
        return None

    first = nestedLis[0]
    if isinstance(first, list):
        min_first = recMin(first)
    else:
        min_first = first

    if len(nestedLis) == 1:
        return min_first
    else:
        min_others = recMin(nestedLis[1:])
        if min_first < min_others:
            return min_first
        else:
            return min_others

print("Minimum: ", recMin([3, 5, 3, 5, [3, 1, 5, 3], [3, 2, 5]]))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM