how this tricky problem could be solved in python for creating subarray

162 Views Asked by At

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]

1

There are 1 best solutions below

3
On

Use of itertools.combinations would be best here:

from itertools import combinations

arr = [1, 2, 8, 6, 4, 9, 5]
k = 3
target = 10

subsets = [comb for comb in combinations(arr, k) if sum(comb) == target]
print(subsets)

This results in list of tuple not list 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:

def combinations(arr, k):
    if k == 0:
        return [[]]
    if not arr:
        return []
    head, *tail = arr
    return [[head] + combo for combo in combinations(tail, k - 1)] + combinations(tail, k)