简体   繁体   中英

Finding the minimum from a nested list using recursion

I am trying to write a function to find the minimum value of a nested list. I have written code but get the error that I cannot use < between an integer and a list. Any ideas? I cannot use any built-in functions.

def minimumVal(Y):
   if len(Y) == 1:
      return Y[0]
   minimum = Y[0]
   if minimum < minimumVal(Y[1:]):
      return minimum
   else:
      return minimumVal(Y[1:])

My first thought would be to collapse the list with itertools but since you can't use built in functions, here's a scrappy method that works:

l = [2, 3, 4, 5, 6, [3, 4, 5, 10], [15, 4, 9, 8]]
minimum = []
for sublist in l:
    try:
        for num in sublist:
            if len(minimum) == 0:
                minimum.append(num)
            else:
                if num < minimum[0]:
                    minimum[0] = num
    except:
        if len(minimum) == 0:
            minimum.append(sublist)
        else:
            if sublist < minimum[0]:
                minimum[0] = num

print(minimum[0])

output: 2

if you can't use len(), here's another option with more tries/excepts:

l = [2, 3, 4, 5, 6, [3, 4, 5, 10], [15, 4, 9, 8]]
minimum = []
for sublist in l:
    try:
        for num in sublist:
            try:
                if num < minimum[0]:
                    minimum[0] = num
            except IndexError:
                    minimum.append(num)
    except:
        try:
            if sublist < minimum[0]:
                minimum[0] = sublist
        except IndexError:
                minimum.append(sublist)

print(minimum[0])

output: 2

Last option, if you can't use the built in function for append you can do this:

l = [3, 4, 5, 6, 2, [3, 4, 5, 10], [15, 4, 9, 8]]
minimum = ['place holder']
for sublist in l:
    try:
        for num in sublist:
            if minimum[0] != 'place holder':
                if num < minimum[0]:
                    minimum[0] = num
            else:
                    minimum[0] = num
    except:
        if minimum[0] != 'place holder':
            if sublist < minimum[0]:
                minimum[0] = sublist
        else:
                minimum[0] = sublist

print(minimum[0])

output: 2

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