Join Regular Classroom : Visit ClassroomTech

Combination And Its Sum – Infytq 2019 Solve

Problem: A set of number will be given and a sum will also be given. Print the number of combinations possible of length 4 which sums up to be the given sum.

Input format: First line contains the given set of numbers. Second line contains a single integer denoting the sum.

Sample Input:

-1,1,0,2,-2
0

Sample Output:

3

Explanation: All the possible combinations of length 4 which will add up to be 0 are (-1, 1, 2, -2), (0, 0, 1, -1), (0, 0, -2, 2)

First combination: -1+1+2+(-2) = 0
Second combination: 0+0+1+(-1) = 0
Third combination: 0+0+(-2)+2 = 0

Hence, the output will be 3.

Solution: We strongly recommend you to try the problem first before moving to the solution.

Python

import itertools
input_set = list(map(int,input().split(",")))
s = int(input())
combination_list=list(itertools.combinations(input_set, 4))
count=0
for obj in combination_list:
    obj_sum = sum(obj)
    if (obj_sum == s):
        count+=1
print(count)

Input:

-1,1,0,2,-2
0

Output:

3

Follow Us

You Missed