Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to find the array containing the smallest value?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading