Finding a tuple from list of tuples having a difference by one or two with input tuple

Viewed 48

I have a reference list of tuple

ref_list = [(31, 38), (56, 61)]

which inputs are given like below

input ----> [(24, 29)]  output----> (31,38)
input ----> [(74, 82)]  output----> None
input ----> [(49, 55)]  output----> (56,71)

How is it possible to find the tuple from a list which has difference between first element of reference tuple and second element in the input tuple by one or two ?

3 Answers
ref_list = [(31, 38), (56, 61)]

def find_ref(input_tuple):
    matched_tuples = []
    for ref in ref_list:
        if (abs(input_tuple[1] - ref[0]) <= 2):
            matched_tuples.append(ref)

    return matched_tuples

print(find_ref((24, 29)))
print(find_ref((74, 82)))
print(find_ref((49, 55)))

Ouput:

[(31, 38)]
[]
[(56, 61)]

Here's a way to get the output your question describes:

def foo(inp, ref_list, tolerance):
    for ref in ref_list:
        if abs(ref[0] - inp[1]) <= tolerance:
            return ref
    return None
ref_list = [(31, 38), (56, 71)]
inputs = [(24, 29), (74, 82), (49, 55)]
[print(f"input ----> {[inp]}  output----> {foo(inp, ref_list, 2)}") for inp in inputs]

Output:

input ----> [(24, 29)]  output----> (31, 38)
input ----> [(74, 82)]  output----> None
input ----> [(49, 55)]  output----> (56, 71)

Note that this returns the first tuple in ref_list which is a match to each given input tuple.

REFERENCE_LIST = [(31, 38), (56, 61)]

# find the tuple (i.e. one tupple, i.e. the first) from REFERENCE_LIST which 
# has difference between first element of reference tuple e.g a_reference_tupple[0] and
# the second element in the input tuple input_tuple[1] by one or two i.e.: 0 < abs(the_difference) < 3
def the_tupple_within_criteria(input_tuple):
    for a_reference_tuple in REFERENCE_LIST: #interate over the reference list
        if 0 < abs( a_reference_tuple[0] - input_tuple[1]) < 3: #is the criteria met
            return a_reference_tuple

# Test
print(the_tupple_within_criteria((24, 29))) #(31,38)
print(the_tupple_within_criteria((74, 82))) #None
print(the_tupple_within_criteria((49, 55))) #(56,71)
Related