write a program to create subset of given array the value inside the array should be target value and length of array should be k
program that i have tried
arr = [1, 2, 8, 6, 4, 9, 5]
k = 3
target = 10
sub = []
res = []
for i in arr:
sub.append(i)
if len(sub) == k:
if sum(sub) == target:
res.append(sub[:])
sub.pop(0)
print(res)
sample input:
arr = [1,2,3,6,4,9,5]
k = 3
target = 10
output =:
[1,4,5]
Use of itertools.combinations would be best here:
This results in
list
oftuple
notlist
to consider the chances of having other such combinations, despite the example showcasing only one.If you want a custom
combinations
function you can create one by use of recursion: