MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / is_sum_subset

Function is_sum_subset

dynamic_programming/sum_of_subset.py:1–29  ·  view source on GitHub ↗

>>> is_sum_subset([2, 4, 6, 8], 5) False >>> is_sum_subset([2, 4, 6, 8], 14) True

(arr: list[int], required_sum: int)

Source from the content-addressed store, hash-verified

1def is_sum_subset(arr: list[int], required_sum: int) -> bool:
2 """
3 >>> is_sum_subset([2, 4, 6, 8], 5)
4 False
5 >>> is_sum_subset([2, 4, 6, 8], 14)
6 True
7 """
8 # a subset value says 1 if that subset sum can be formed else 0
9 # initially no subsets can be formed hence False/0
10 arr_len = len(arr)
11 subset = [[False] * (required_sum + 1) for _ in range(arr_len + 1)]
12
13 # for each arr value, a sum of zero(0) can be formed by not taking any element
14 # hence True/1
15 for i in range(arr_len + 1):
16 subset[i][0] = True
17
18 # sum is not zero and set is empty then false
19 for i in range(1, required_sum + 1):
20 subset[0][i] = False
21
22 for i in range(1, arr_len + 1):
23 for j in range(1, required_sum + 1):
24 if arr[i - 1] > j:
25 subset[i][j] = subset[i - 1][j]
26 if arr[i - 1] <= j:
27 subset[i][j] = subset[i - 1][j] or subset[i - 1][j - arr[i - 1]]
28
29 return subset[arr_len][required_sum]
30
31
32if __name__ == "__main__":

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected