Three number sum target

 # Online Python compiler (interpreter) to run Python online.

# Write Python 3 code in this online editor and run it.



def two_sum(arr,l,h,target):

    lis=[]

    while l<h:

        if arr[l]+arr[h]==target:

            lis.append([arr[l],arr[h]])

            l+=1

            h-=1

        elif arr[l]+arr[h]>target:

            h-=1

        elif arr[l]+arr[h]<target:

            l+=1

    return lis

    

    

def three_sum(arr,target):

    res=[]

    for i in range (0,len(arr)-1) :

        

        lis=[]

        lis=two_sum(arr,i+1,len(arr)-1,target-arr[i])

        print (arr[i])

        print(lis)

        if lis==[]:

            i+=1

        else:

            for j in range(0,len(lis)):

                lis[j].append(arr[i])

            print(lis)

            res.append(lis)

            

    return res

        

        

arr=[12,3,1,2,-6,5,-8,6]

target=0



arr.sort()

print(arr)

lis=three_sum(arr,target)

print(lis)

Comments

Popular posts from this blog

Sum of Even Numbers till N

Find the Runner-Up Score!

Print All Substrings