pythonlistdifference

Values for which the difference is the closest to a specific number


Currently, I am looking into a Python problem where I would like to find the two values in a list, for which the difference is the closest to a specific number.

For example, I would like to find the two values in A for which the difference is the closest to 2.

A = [1,5,9,10,20,7]

In this case, the answer needs to be 5 and 7.

The constrain is that you always will do A[N+x] - A[N]. For instance, you are not allowed to do 5-9. In that case, it will always be 9-5

Would this be possible in Python?


Solution

  • Isn't the difference of 5,7 and 9,7 closer to 2 than 9,10 given that those differences are exactly 2? I'm not sure if you're discounting all pairs whose differences that are exactly 2. Here's some code that you can modify accordingly if you need to discount values whose difference are exactly 2.

    import itertools
    
    list_ = [1,5,9,10,20,7]
    all_pairs = list(itertools.combinations(list_, 2))
    pairs = {key:key[0]-key[1] if key[0]-key[1]>=0 else key[1]-key[0] for key in 
    all_pairs}
    
    def takeClosest(num,collection):
        return min(collection,key=lambda key_: abs(collection[key_]-num))
    
    print(takeClosest(2,pairs))
    

    Hope that helps, if not, please clarify the 9,10 example a bit more.