1
def subset_sum(numbers, target, partial=[], partial_sum=0):
    if partial_sum == target:
        yield partial
    if partial_sum >= target:
        return
    for i, n in enumerate(numbers):
        remaining = numbers[i + 1:]
        yield from subset_sum(remaining, target, partial + [n], partial_sum + n)
    
list = [ ]
no=int(input("Enter the count of the List: "))
s=float(input("Enter the target value: "))
for c in range (1,no):
    temp=(input("Value "+str(c)+"= " ))
    list.extend(map(float, temp.split(", ")))
    
print(list)
subset_sum(list,s,no)

The objective of the program is to find all the possible combination to reach the specific target. The problem is, it doesn't print the partial after finding the combinations.

Barmar
  • 741,623
  • 53
  • 500
  • 612
Audenzia
  • 11
  • 1
  • 1
    Does this answer your question? [Finding all possible combinations of numbers to reach a given sum](https://stackoverflow.com/questions/4632322/finding-all-possible-combinations-of-numbers-to-reach-a-given-sum) – Max Feb 05 '22 at 07:46

1 Answers1

0
def subset_sum(numbers, target, partial=[], partial_sum=0):
    if partial_sum == target:
        yield partial
    if partial_sum >= target:
        return
    for i, n in enumerate(numbers):
        remaining = numbers[i + 1:]
        yield from subset_sum(remaining, target, partial + [n], partial_sum + n)
    
nums = [ ]
no=int(input("Enter the count of the List: "))
s=float(input("Enter the target value: "))
for c in range (1,no+1):
    temp=(input("Value "+str(c)+"= " ))
    nums.extend(map(float, temp.split(", ")))
    
print(nums)
print(list(subset_sum(nums,s)))

There were a few bugs in your program:

  1. Generator objects don't produce data unless asked for. So, you need to extract them from the generator object by creating a list out of it or explicitly iterating over it. That's why I changed the last line to:
print(list(subset_sum(nums,s)))
  1. It is never a good idea to name a list, list. In this case it would have overwritten list and my use of list on the last line wouldn't work. So, I changed it to nums.
  2. In your original code you pass it no as the third argument of subset_sum. no is the length of nums (of type integer) while the third parameter of subset_sum is the partial result of type list. Since it has a default value we don't even need to pass in the third argument.
  3. In your input routine, you loop from 1 to no. This would leave you one element short of the requested length of nums since the upper bound of a for loop is exclusive.
user1984
  • 5,990
  • 2
  • 13
  • 32