简体   繁体   中英

Find the a pair of tuple with the closest sum to a given number

I try to define a function that takes in a list & an int and gives back a tuple of the list element that sums up to the int.

I try to loop through all elements in the alternateSumList to give all possible tuples. However, I got only 1 possibility with a wrong order.

def closestPairsAlt(List, value):
    calculateDifferenceList = [value - x for x in List]
    alternateSumList = []
    for i in range(len(calculateDifferenceList)):
        if calculateDifferenceList[i]>=0:
            alternateSumList.append([calculateDifferenceList[i]+List[i], i, List[i]])
    for x in range(len(alternateSumList)):
        val1 = alternateSumList[x][2]
        searchValue = value - val1
        if searchValue in List:
            val2 = searchValue
        else:
            pass

    return(val1, val2)

List = [1,3,5,7,9]
value = 8

Short one-liner with itertools.combinations feature:

from itertools import combinations

def closest_pair_sum(lst, value):
    return list(t for t in combinations(lst, r=2) if sum(t) == value)

lst = [1,3,5,7,9]
value = 8
print(closest_pair_sum(lst, value))

The output:

[(1, 7), (3, 5)]

How about this?

import itertools

def f(items, val):
    for i, j in itertools.combinations(range(len(items)), 2):
        if items[i] + items[j] == val:
            print(items[i], items[j])

list = [1,2,5,7,9]
f(list, 8)
(1, 7)
(3, 5)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM