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

Find elements' indices with maximum difference between two lists

There are two lists

l1 = [1, 2.3, 1.4, 1.1]

l2 = [2.1, 0.9, 1.1, 3.2]

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

and I want to find the elements in the lists that have the maximum difference between the lists.

I.e.:

l1 = [1, 2.3, 1.4, 1.1] should return 0 for index 0 of the smallest number

l2 = [2.1, 0.9, 1.1, 3.2] should return 3 for index 3 of the highest number

>Solution :

Try this:

l1 = [1, 2.3, 1.4, 1.1]
l2 = [2.1, 0.9, 1.1, 3.2]


def max_diff(l1, l2):
    min_l1 = min(l1)
    max_l1 = max(l1)
    min_l2 = min(l2)
    max_l2 = max(l2)
    max_diff1 = max_l2 - min_l1
    max_diff2 = max_l1 - min_l2
    if max_diff1 > max_diff2:
        return l1.index(min_l1), l2.index(max_l2), max_diff1
    else:
        return l1.index(max_l1), l2.index(min_l2), max_diff2


l1_index, l2_index, max_diff = max_diff(l1, l2)
print(l1_index, l2_index, max_diff)  # 0 3 2.2

Note that this computes the max difference and can return either the (min(l1), max(l2)) or (max(l1), min(l2)) depending on the items in the list.

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