-
-
Notifications
You must be signed in to change notification settings - Fork 50.4k
Expand file tree
/
Copy pathsum_of_subset.py
More file actions
43 lines (34 loc) · 1.4 KB
/
sum_of_subset.py
File metadata and controls
43 lines (34 loc) · 1.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
def is_sum_subset(arr: list[int], required_sum: int) -> bool:
"""
>>> is_sum_subset([2, 4, 6, 8], 5)
False
>>> is_sum_subset([2, 4, 6, 8], 14)
True
"""
# a subset value says 1 if that subset sum can be formed else 0
# initially no subsets can be formed hence False/0
arr_len = len(arr)
subset = [[False] * (required_sum + 1) for _ in range(arr_len + 1)]
# for each arr value, a sum of zero(0) can be formed by not taking any element
# hence True/1
for i in range(arr_len + 1):
subset[i][0] = True
# sum is not zero and set is empty then false
for i in range(1, required_sum + 1):
subset[0][i] = False
for i in range(1, arr_len + 1):
for j in range(1, required_sum + 1):
current_item_value = arr[i - 1]
# current_item_value is greater than j
if current_item_value > j:
subset[i][j] = subset[i - 1][j]
# replace an 'if' in an 'else' to make the fluxe more clean
else:
without_current_item = subset[i - 1][j]
sum_required_if_item_taken = j - current_item_value
without_current_item = subset[i - 1][sum_required_if_item_taken]
subset[i][j] = without_current_item or without_current_item
return subset[arr_len][required_sum]
if __name__ == "__main__":
import doctest
doctest.testmod()