How to print all distinct 4 elements from a list that have the same given sum in Python

1 Answer

0 votes
def getDistinct4Elements(lst, target):
    lst.sort()
 
    for i in range(len(lst) - 3):
        for j in range(i + 1, len(lst) - 2):
            k = target - (lst[i] + lst[j])
 
            fromstart = j + 1
            fromend = len(lst) - 1
 
            while fromstart < fromend:
                if lst[fromstart] + lst[fromend] < k:
                    fromstart = fromstart + 1
                elif lst[fromstart] + lst[fromend] > k:
                    fromend = fromend - 1
                else:
                    print(lst[i], lst[j], lst[fromstart], lst[fromend])
                    (fromstart, fromend) = (fromstart + 1, fromend - 1)
 
 
lst = [4, 8, 1, 5, 9, 0, 3, 7]

sum = 18
 
getDistinct4Elements(lst, sum)




'''
run:

0 1 8 9
0 3 7 8
0 4 5 9
1 3 5 9
1 4 5 8

'''

 



answered Aug 20, 2022 by avibootz
...