Answer to Question #183890 in Python for phani

Question #183890
K Sum Unique Combinations
Given a list of integers, write a program to print the count of all possible unique combinations of numbers whose sum is equal to K.
Input

The first line of input will contain space-separated integers.
The second line of input will contain an integer, denoting K.
Output

The output should be containing the count of all unique combinations of numbers whose sum is equal to K
All possible unique combinations of the given list are

(6,) (2,) (4,) (1,) (3,)
(2, 4) (1, 2) (3, 4) (4, 6) (1, 4) (2, 3) (2, 6) (3, 6) (1, 6) (1, 3)
(3, 4, 6) (2, 3, 6) (1, 2, 6) (1, 2, 3) (1, 4, 6) (1, 3, 4) (2, 3, 4) (1, 3, 6) (2, 4, 6) (1, 2, 4)
(2, 3, 4, 6) (1, 2, 3, 4) (1, 2, 4, 6) (1, 2, 3, 6) (1, 3, 4, 6)
(1, 2, 3, 4, 6)

-1 4 5 6 7 8 2 4 5 2 3 8
7

The unique combinations with the sum equal to 7 are

7
-1 8
3 4
2 5
-1 3 5
-1 4 4
-1 2 6
2 2 3
-1 2 2 4
Sample Input 1
2 4 6 1 3
6
Sample Output 1
3

Sample Input 2
-1 4 5 6 7 8 2 4 5 2 3 8
7
Sample Output 2
9



1
Expert's answer
2021-04-21T07:41:01-0400
from itertools import combinations
#The first line of input will contain space-separated integers.
values =[int(i) for i in input('Enter space-separated integers: ').split()]
values.sort()
#The second line of input will contain an integer, denoting K.
K = int(input('Enter K: '))
#The output should be containing the count of all unique combinations of numbers whose sum is equal to K
counterUniqueCombinations=0
print(f"The unique combinations with the sum equal to {K} are:")
for i in range(1, len(values)+1):
    com =list(set(combinations(values, i)))
    for combination in com:
        if sum(combination) == K:
            print(combination)
            counterUniqueCombinations += 1
print(f"The count of all unique combinations is: {counterUniqueCombinations}")





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