Reputation: 2844
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.
Upvotes: 0
Views: 99
Reputation: 6776
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))
Upvotes: 2
Reputation: 170
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])
Upvotes: 1
Reputation: 779
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]
Upvotes: 1