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.
The output should be containing the count of all unique combinations of numbers whose sum is equal to K.
Sample Input 1
2 4 6 1 3
6
Sample Output 1
3
CODE:
---------
from itertools import combinations
# Get a list of numbers from input
numbers = [int(n) for n in input().split()]
# Get K value from input
k = int(input())
# Count combinations that sum to K
count = 0
# Try combinations of all possible sizes
for i in range(1, len(numbers)+1):
# Try all combinations of size i
for c in combinations(numbers, i):
# If this combination sums to K, then increase the count
if sum(c) == k:
count += 1
# Output the count
print(count)
In the above code, using import tools like combinations.
Can you please help me to write the code without using import tools?
def powerset(seq):
"""
Returns all the subsets of this set. This is a generator.
"""
if len(seq) <= 1:
yield seq
yield []
else:
for item in powerset(seq[1:]):
yield [seq[0]]+item
yield item
num = [int(item) for item in input().split()]
n = int(input())
res = 0
for subset in powerset(num):
if sum(subset) == n:
res += 1
print(res)
Comments
Leave a comment