Home > Enterprise >  How to find the array containing the smallest value?
How to find the array containing the smallest value?

Time:08-30

I have an array of sub-arrays of numbers, and I want to find the sub-array containing the smallest number.

data = [
    [10, 11],
    [93, 3], # This is the required sub-array because 3 is smaller than all the other numbers
    [33, 44, 55]
]

# tag the smallest item from each sub-array onto the front, creating a new main array
extendedData = map(lambda x:(min(x), x),data)

# use the fact that when given an array, min() will examine the first element
(smallestValueFromRow, rowContainingSmallestValue) = min(extendedData)

print(rowContainingSmallestValue)

Here's a working example: https://www.online-python.com/7O5SceGoEF

Is there a more memory-efficient way to approach this? The array and sub-arrays could be quite large in practice, and I'm assuming the map function makes a copy of the data array, with the mapping applied.

CodePudding user response:

Here is a solution which will return the first list which contains the minimum value:

data = [
    [10, 11],
    [93, 3], 
    [33, 44, 55]
]    

smallestNumbersFromEachSubList = [min(subList) for subList in data]
subListContainingTheSmallestNumber = data[smallestNumbersFromEachSubList.index(min(smallestNumbersFromEachSubList))]
print(subListContainingTheSmallestNumber)

This would return:

[93, 3]
  • Related