Skip to content

Commit 65a12fa

Browse files
jpg-130poyea
authored andcommitted
Adding sum of subsets (#929)
1 parent 0f56ab5 commit 65a12fa

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

Diff for: dynamic_programming/sum_of_subset.py

+34
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
def isSumSubset(arr, arrLen, requiredSum):
2+
3+
# a subset value says 1 if that subset sum can be formed else 0
4+
#initially no subsets can be formed hence False/0
5+
subset = ([[False for i in range(requiredSum + 1)] for i in range(arrLen + 1)])
6+
7+
#for each arr value, a sum of zero(0) can be formed by not taking any element hence True/1
8+
for i in range(arrLen + 1):
9+
subset[i][0] = True
10+
11+
#sum is not zero and set is empty then false
12+
for i in range(1, requiredSum + 1):
13+
subset[0][i] = False
14+
15+
for i in range(1, arrLen + 1):
16+
for j in range(1, requiredSum + 1):
17+
if arr[i-1]>j:
18+
subset[i][j] = subset[i-1][j]
19+
if arr[i-1]<=j:
20+
subset[i][j] = (subset[i-1][j] or subset[i-1][j-arr[i-1]])
21+
22+
#uncomment to print the subset
23+
# for i in range(arrLen+1):
24+
# print(subset[i])
25+
26+
return subset[arrLen][requiredSum]
27+
28+
arr = [2, 4, 6, 8]
29+
requiredSum = 5
30+
arrLen = len(arr)
31+
if isSumSubset(arr, arrLen, requiredSum):
32+
print("Found a subset with required sum")
33+
else:
34+
print("No subset with required sum")

0 commit comments

Comments
 (0)