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:
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