Skip to content

Commit c82f6bc

Browse files
Restructure Subset sum problem to have function return subset or None if not found
1 parent 9f28c49 commit c82f6bc

File tree

1 file changed

+21
-7
lines changed

1 file changed

+21
-7
lines changed

Scripts/Subset sum problem.py

Lines changed: 21 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -28,36 +28,51 @@ def find_subset(weight, req_sum):
2828
else:
2929
dp_array[i][j]=dp_array[i-1][j]
3030

31-
print("Subset for sum",req_sum,' :')
32-
3331
#Find out which Numbers should be in the subset
3432
#give from index 0
3533
row-=1
3634
col-=1
35+
sum_subset=[]
36+
37+
#check if the Subset is possible : if not, return None
38+
if dp_array[row][col] != req_sum :
39+
return None
40+
41+
#get the subset
3742
while col>=0 and row>=0 and req_sum>0:
3843
#First Row
3944
if(row==0):
40-
print(weight[row])
45+
sum_subset.append(weight[row])
4146
break
4247

4348
#Bottom-Right most ele
4449
if(dp_array[row][col]!=dp_array[row-1][col]):
4550
# print(req_sum,' : ',dp_array[row][col],dp_array[row-1][col],' : ',weight[row])
46-
print(weight[row])
51+
sum_subset.append(weight[row])
4752
req_sum-=weight[row]
4853
col-=weight[row]
4954
row-=1
5055
else:
5156
row-=1
5257

58+
return sum_subset
59+
60+
5361
#main
5462
if __name__=="__main__":
5563
array=list(map(int,input().split()))
5664
req_sum=int(input())
5765

5866
#Sort by ascending order
5967
array.sort()
60-
find_subset(array,req_sum)
68+
sum_subset = find_subset(array,req_sum)
69+
70+
#If Sum is not possible
71+
if sum_subset is None :
72+
print("Sum :",req_sum,"is not possible")
73+
else:
74+
print("Subset for sum",req_sum,' :')
75+
print(' '.join(str(x) for x in sum_subset))
6176

6277
"""
6378
Input Explanation :
@@ -70,8 +85,7 @@ def find_subset(weight, req_sum):
7085
7186
Output :
7287
Subset for sum 13 :
73-
8
74-
5
88+
8 5
7589
7690
"""
7791

0 commit comments

Comments
 (0)