How to find the array containing the smallest value?

Question:

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.

Asked By: OutstandingBill

||

Answers:

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]
Answered By: lummers

Since you asked for a memory-efficient implementation, this approach will be constant space

min_num = min_idx = float("inf")
for i, nums in enumerate(data):
    local_min = min(nums)
    if local_min < min_num:
        min_idx = i
    min_num = min(min_num, local_min)
print(data[min_idx])
Answered By: mj_codec

Your first solution, using map, should not require more than constant extra space, since map returns a generator — it doesn’t actually do anything until you iterate over it.

However, you can do effectively the same thing with less typing:

print(min(data, key=min))
Answered By: Ture Pålsson
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.