Getting unique minimum value indices in multiple lists

I am having problems with my problem.

Say I have n lists, each of which contains n elements. For each list, I need to find the minimum value index and save it in a new list. It is quite simple.

The problem is that two or more values ​​in my index list may be equal. I need a list with unique values. If two (or more) values ​​are equal, I want to determine the priority of the index value that came from the minimum value of the minima.

Example:

myLists = []
myLists.append([113.6, 12262.6, 21466.7, 141419.9])      # list 1
myLists.append([122284.8, 111161.8, 106581.1, 141419.9]) # list 2
myLists.append([25427.9, 13694.0, 5148.9, 141419.9])     # list 3
myLists.append([21354.9, 10599.2, 0.1, 141419.9])        # list 4

This will give me an index list [0,2,2,2]. Based on the second value in lists 2, 3, and 4, I see that the smallest of them is on list 4, so my index list should look like [0,?,?, 2].

Next, I need to fill in the question marks with values ​​1 and 3, but where? From the check, I see that with 13694.0 (index 1 from list 3) less than 111161.8 (index 1 from list 2), and the third index values ​​in each list are equal, I have to select index 1 from list 3.

This means that my new index list is [0,?, 1,2]. There is only one question mark left, I fill in this 3. This gives [0,3,1,2].

The lists will be mostly small, so the runtime is not really a problem.

+4
source share
1 answer

I combined all the lists as three member tuples (value, list index in myLists, index of the value in the list) and sorted it by value. The temporary complexity of my code is nlog (n).

myLists = []
myLists.append([113.6, 12262.6, 21466.7, 141419.9])  # list 1
myLists.append([122284.8, 111161.8, 106581.1, 141419.9])  # list 2
myLists.append([25427.9, 13694.0, 5148.9, 141419.9])  # list 3
myLists.append([21354.9, 10599.2, 0.1, 141419.9])  # list 4

merged_list = list()

for index1, ls in enumerate(myLists):
    for index2, x in enumerate(ls):
        merged_list.append((x, index1, index2))

merged_list.sort()

st = set()  #to store already added indices

res = [-1 for i in range(len(myLists))]

for x, y, z in merged_list:
    if res[y] != -1 or z in st:
        continue
    res[y] = z
    st.add(z)

print(res)

Output -

[0, 3, 1, 2]
+4
source

All Articles