0

I need to build a recursive function that receives an integer list (numbers) and a non-negative integer (target).

The function will look for any possible subset of the given list and if its values are added up and equal to the target, returns True.

def subset_sum(numbers, target):
    '''
    numbers - a list of positive integers
    target - a non-negative integer
    returns True if the list 'numbers' has a sub-list with sum 'target',
            False otherwise.
    '''

Side Note: [] is a subset of any given list (set)

Examples:

subset_sum([1,2,3,4], 8):

True

subset_sum([1,2,3,4], 11):

False

subset_sum([4,4,4], 05):

True

subset_sum([4,4,4], 11):

False

subset_sum([], 0):

True

Any help appreciated!

John Coleman
  • 51,337
  • 7
  • 54
  • 119
Menkes
  • 63
  • 1
  • 1
  • 9

1 Answers1

0

This is a variant (sub-problem) on the subset sum problem which you can read about here:

https://en.wikipedia.org/wiki/Subset_sum_problem

There is a pseudocode algorithm outlined that solves the problem approximately in polynomial time for any integers (positive or negative). Interestingly enough this is posted on Stackoverflow and in python!

Fast solution to Subset sum

Community
  • 1
  • 1
user3261832
  • 45
  • 1
  • 7