Skip to content

adding sum of subsets #929

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

Merged
merged 1 commit into from
Jul 2, 2019
Merged
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
34 changes: 34 additions & 0 deletions dynamic_programming/sum_of_subset.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
def isSumSubset(arr, arrLen, requiredSum):

# a subset value says 1 if that subset sum can be formed else 0
#initially no subsets can be formed hence False/0
subset = ([[False for i in range(requiredSum + 1)] for i in range(arrLen + 1)])

#for each arr value, a sum of zero(0) can be formed by not taking any element hence True/1
for i in range(arrLen + 1):
subset[i][0] = True

#sum is not zero and set is empty then false
for i in range(1, requiredSum + 1):
subset[0][i] = False

for i in range(1, arrLen + 1):
for j in range(1, requiredSum + 1):
if arr[i-1]>j:
subset[i][j] = subset[i-1][j]
if arr[i-1]<=j:
subset[i][j] = (subset[i-1][j] or subset[i-1][j-arr[i-1]])

#uncomment to print the subset
# for i in range(arrLen+1):
# print(subset[i])

return subset[arrLen][requiredSum]

arr = [2, 4, 6, 8]
requiredSum = 5
arrLen = len(arr)
if isSumSubset(arr, arrLen, requiredSum):
print("Found a subset with required sum")
else:
print("No subset with required sum")