Home > Software engineering >  Compare multiple lists with same structure for the one with smaller integers at lowest positions
Compare multiple lists with same structure for the one with smaller integers at lowest positions

Time:05-11

I have multiple lists (arbitrary number of lists, not pre-set) of the type [65, 34, 13, 6] and all elements have diminishing sizes from index [0] to length (e.g. 65 > 34 > 13 > 6). I want to compare all of them and keep the one that has the smallest integers, ranked by highest index. For example:

Input:

[165, 54, 33, 6]
[165, 34, 24, 6]
[65, 23, 13, 6]
[65, 55, 5, 6]

Should output:

[65, 55, 5, 6]

since the 5 is the smallest integer compared to 13, 24 and 33 at the highest position that doesn't have equal values. In the example above, the all lists have equal value at highest index (length-1 slot) so we need to compare the [length-2] slot. There, the smallest of values is 5, so the algorithm stops here and returns the last list with 5 at [length-2] index.

If all elements in [-1] and [-2] where equal, check should utilize the next highest index.

The answer must not combine different values from multiple lists, it must choose one of the existing lists with the lowest value at the highest position.

Is there a fast way to execute such a comparison? Thanks!

CodePudding user response:

Since your lists are decreasing, you can use:

idx, val = [(i, min(vals)) for i, vals in enumerate(zip(*lsts)) if len(set(vals))>1][-1]
output = [l for l in lsts if l[idx]==val][0]
Examples:
lsts = [[165, 54, 33, 6], 
        [165, 34, 24, 6], 
        [65, 23, 13, 6], 
        [65, 55, 5, 6]]

idx, val = [(i, min(vals)) for i, vals in enumerate(zip(*lsts)) if len(set(vals))>1][-1]
>>> [l for l in lsts if l[idx]==val][0]
[65, 55, 5, 6]

lsts = [[165, 54, 24, 6], 
        [165, 34, 24, 6], 
        [65, 23, 24, 6], 
        [65, 55, 24, 6]]

idx, val = [(i, min(vals)) for i, vals in enumerate(zip(*lsts)) if len(set(vals))>1][-1]
>>> [l for l in lsts if l[idx]==val][0]
[65, 23, 24, 6]

CodePudding user response:

You can do it by using the zip function to group all elements by index then use the min function on it to get the minimum at each position :

l1 = [165, 54, 33, 6]
l2 = [165, 34, 24, 6]
l3 = [65, 23, 13, 6]
l4 = [65, 55, 5, 6]

output = [min(elements) for elements in zip(l1, l2, l3, l4)]
  • Related