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

Returning the other value of the pair from a tuple, which has closest value to certain number

I have a list of tuples like this:

[(78, 10), (84, 11), (75, 12), (78, 13), (75, 14), (77, 15), (79, 16), (81, 17), (83, 18), (85, 19)]

How can I do like, if the first number in any of the tuples is closest/equal to a certain number, return the other pair value from that tuple?

for example in the list above:

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

certain number: 79
then it should return 16 from the above list.

Thanks!

>Solution :

You have a couple of options.

Method 1:

Iterate over the list and check for the smallest difference.

def return_closest_pair(data: list, target: int) -> int:
    closest, other = data[0]
    closest_diff = abs(closest - target)
    rest = iter(data[1:])
    for left, right in rest:
        diff = abs(left - target)
        if diff < closest_diff:
            closest, other = left, right
    return other

>>> return_closest_pair(data, 79)

Method 2:

Write a custom key for min function, as you had originally tried.

def find_closest_to(target):
    def comp(tup):
        left, right = tup
        return abs(left - target)
    return comp

>>> min(data, key=find_closest_to(79))[0]
16
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