Answer to Question #219064 in Python for Krish

Question #219064

Write a program to print the count of all possible unique combinations of numbers whose sum is equal to K


1
Expert's answer
2021-07-20T02:32:34-0400



def unique_combination(l, sum, K, local, A):
 

    
    
    if (sum == K):
        

        print("{", end="")

        for i in range(len(local)):

            if (i != 0):

                print(" ", end="")

            print(local[i], end="")

            if (i != len(local) - 1):

                print(", ", end="")

        print("}")

        return
 

    

    for i in range(l, len(A), 1):
 

        

        if (sum + A[i] > K):

            continue
 

        

        if (i > l and

                A[i] == A[i - 1]):

            continue
 

         

        local.append(A[i])
        
 

        

        unique_combination(i + 1, sum + A[i],

                           K, local, A)
 

        

        local.remove(local[len(local) - 1])
 

 
 

def combination(A, K):
 

    

    A.sort(reverse=False)
 

    local = []
 

    unique_combination(0, 0, K, local, A)
 
 


if __name__ == '__main__':

    A = [2,4,6,1,3]
 

    K = 3
 



    combination(A, K)

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS