Skip to content

Add tests and cleanup sum_of_subsets algorithm #12746

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 17 additions & 15 deletions backtracking/sum_of_subsets.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,25 @@
"""
The sum-of-subsetsproblem states that a set of non-negative integers, and a
The sum-of-subsets problem states that a set of non-negative integers, and a
value M, determine all possible subsets of the given set whose summation sum
equal to given M.

Summation of the chosen numbers must be equal to given number M and one number
can be used only once.
"""

from __future__ import annotations

def generate_sum_of_subsets_solutions(nums: list[int], max_sum: int) -> list[list[int]]:
"""
The main function. For list of numbers 'nums' find the the subsets with sum
equal to 'max_sum'
>>> generate_sum_of_subsets_solutions([3, 34, 4, 12, 5, 2], 9)
[[3, 4, 2], [4, 5]]
>>> generate_sum_of_subsets_solutions([3, 34, 4, 12, 5, 2], 3)
[[3]]
>>> generate_sum_of_subsets_solutions([3, 34, 4, 12, 5, 2], 1)
[]
"""

def generate_sum_of_subsets_soln(nums: list[int], max_sum: int) -> list[list[int]]:
result: list[list[int]] = []
path: list[int] = []
num_index = 0
Expand All @@ -34,7 +43,9 @@ def create_state_space_tree(
This algorithm follows depth-fist-search and backtracks when the node is not
branchable.

>>> create_state_space_tree([1], 1, 0, [], [], 1)
"""

if sum(path) > max_sum or (remaining_nums_sum + sum(path)) < max_sum:
return
if sum(path) == max_sum:
Expand All @@ -51,16 +62,7 @@ def create_state_space_tree(
)


"""
remove the comment to take an input from the user

print("Enter the elements")
nums = list(map(int, input().split()))
print("Enter max_sum sum")
max_sum = int(input())
if __name__ == "__main__":
import doctest

"""
nums = [3, 34, 4, 12, 5, 2]
max_sum = 9
result = generate_sum_of_subsets_soln(nums, max_sum)
print(*result)
doctest.testmod()