2022-10-12 22:54:20 +00:00
|
|
|
def is_sum_subset(arr, arr_len, required_sum):
|
2019-10-11 18:29:50 +00:00
|
|
|
"""
|
2022-10-12 22:54:20 +00:00
|
|
|
>>> is_sum_subset([2, 4, 6, 8], 4, 5)
|
2019-10-11 18:29:50 +00:00
|
|
|
False
|
2022-10-12 22:54:20 +00:00
|
|
|
>>> is_sum_subset([2, 4, 6, 8], 4, 14)
|
2019-10-11 18:29:50 +00:00
|
|
|
True
|
|
|
|
"""
|
2019-07-02 15:23:35 +00:00
|
|
|
# a subset value says 1 if that subset sum can be formed else 0
|
2019-10-05 05:14:13 +00:00
|
|
|
# initially no subsets can be formed hence False/0
|
2022-10-12 22:54:20 +00:00
|
|
|
subset = [[False for i in range(required_sum + 1)] for i in range(arr_len + 1)]
|
2019-07-02 15:23:35 +00:00
|
|
|
|
2020-06-16 08:09:19 +00:00
|
|
|
# for each arr value, a sum of zero(0) can be formed by not taking any element
|
|
|
|
# hence True/1
|
2022-10-12 22:54:20 +00:00
|
|
|
for i in range(arr_len + 1):
|
2019-07-02 15:23:35 +00:00
|
|
|
subset[i][0] = True
|
|
|
|
|
2019-10-05 05:14:13 +00:00
|
|
|
# sum is not zero and set is empty then false
|
2022-10-12 22:54:20 +00:00
|
|
|
for i in range(1, required_sum + 1):
|
2019-07-02 15:23:35 +00:00
|
|
|
subset[0][i] = False
|
|
|
|
|
2022-10-12 22:54:20 +00:00
|
|
|
for i in range(1, arr_len + 1):
|
|
|
|
for j in range(1, required_sum + 1):
|
2019-10-05 05:14:13 +00:00
|
|
|
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]]
|
2019-07-02 15:23:35 +00:00
|
|
|
|
2019-10-05 05:14:13 +00:00
|
|
|
# uncomment to print the subset
|
2019-07-02 15:23:35 +00:00
|
|
|
# for i in range(arrLen+1):
|
|
|
|
# print(subset[i])
|
2022-10-12 22:54:20 +00:00
|
|
|
print(subset[arr_len][required_sum])
|
2019-07-02 15:23:35 +00:00
|
|
|
|
2019-10-22 17:13:48 +00:00
|
|
|
|
2019-10-11 18:29:50 +00:00
|
|
|
if __name__ == "__main__":
|
|
|
|
import doctest
|
2019-10-05 05:14:13 +00:00
|
|
|
|
2019-10-11 18:29:50 +00:00
|
|
|
doctest.testmod()
|