-5

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]

5
  • This is called the subset sum problem. See towardsdatascience.com/… Commented Nov 2, 2023 at 11:14
  • 1
    @AbhijitSarkar, suggest a free page rather than a page that says: The author made this story available to Medium members only. Upgrade to instantly unlock this story plus other member-only benefits. Commented Nov 2, 2023 at 11:16
  • 1
    @AbhijitSarkar So, don't suggest a link if it does not help. As simple as that. Commented Nov 2, 2023 at 11:23
  • Unironically why was OP downvoted? They actually have their attempt as well in the question. smh 🤦‍♀️. Insert r/programmerhumor StackOverflow helpfulness meme here. Commented Nov 2, 2023 at 11:31
  • 1
    @SashSinha Very likely because the question is pretty common and OP has not demonstrated any research effort. They also didn’t say what their problem is. Commented Nov 2, 2023 at 11:42

1 Answer 1

-1

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)
Sign up to request clarification or add additional context in comments.

2 Comments

This is extremely inefficient to the point of being impractical for large n. If there are n integers in the list, there exist 2^n — 1 subsets that need to be checked (excluding the empty set).
so how can we approach this problem without use of itertools.combination

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.