From 0887629cbd28155c495923cada07faf6f3718009 Mon Sep 17 00:00:00 2001 From: rpjayasekara Date: Mon, 22 Oct 2018 19:43:32 +0530 Subject: [PATCH] Added sub set sum in python --- .../sub set sum/python/subSetSum.py | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 Dynamic Programming/sub set sum/python/subSetSum.py diff --git a/Dynamic Programming/sub set sum/python/subSetSum.py b/Dynamic Programming/sub set sum/python/subSetSum.py new file mode 100644 index 000000000..bf52466d5 --- /dev/null +++ b/Dynamic Programming/sub set sum/python/subSetSum.py @@ -0,0 +1,28 @@ +def isSubsetSum(set,n, sum) : + + # Base Cases + if (sum == 0) : + return True + if (n == 0 and sum != 0) : + return False + + # If last element is greater than + # sum, then ignore it + if (set[n - 1] > sum) : + return isSubsetSum(set, n - 1, sum) + + # else, check if sum can be obtained + # by any of the following + # (a) including the last element + # (b) excluding the last element + return isSubsetSum(set, n-1, sum) or isSubsetSum(set, n-1, sum-set[n-1]) + + +# Test case +set = [3, 34, 4, 12, 5, 2] +sum = 100 +n = len(set) +if (isSubsetSum(set, n, sum) == True) : + print("Found a subset with given sum") +else : + print("No subset with given sum") \ No newline at end of file