I'm trying to solve the sum of subset problem using Python and recursion. The sum of subsets problem is supposed to find if there exists a subset of a set of numbers where the sum of the subset is equal to a target value. I've tried many variations of the code below.
It always stops at the left most deepest branch as far as I can tell.
It is supposed to generate a tree. The tree gets a list of data and a value. The value is 0 at first. It then populates its children. Each node has 2 children. Both children's data is the parent's data with the top value taken off. But the one child will get it added to the value, and one won't.
e.g.
Set: (1, 4, 5, 3, 8)
Target: 4
Subsets: (1, 3), (4)
Tree example (depth till 2nd level):
- 0 (1, 4, 5, 3, 8)
-- 1 (4, 5, 3, 8)
---- 5 (5, 3, 8)
---- 1 (5, 3, 8)
-- 0 (4, 5, 3, 8)
---- 4 (5, 3, 8)
---- 0 (5, 3, 8)
class Tree:
def __init__(self, value, data, target):
self.value = value
self.target = target
self.data = data
self.children = list()
if self.value == target:
print("Target found!")
print(self.children)
print(self.value)
if len(self.data) != 0 and self.value < target:
self.populate()
def populate(self):
top_val = self.data.pop()
self.children.append(Tree(self.value + top_val, self.data, self.target))
self.children.append(Tree(self.value, self.data, self.target))
def print_children(self):
print("value", self.value)
for child in self.children:
child.print_children()
if __name__ == "__main__":
numbers = [3, 34, 4, 12, 5, 2]
tree = Tree(0, numbers, 9)
tree.print_children()
This is the output of the code above:
value 0
value 2
value 7
value 19
value 7
value 11
value 7
value 41
value 7
value 10
value 7
value 2
value 0