-
Notifications
You must be signed in to change notification settings - Fork 12
/
can_partition_bf.py
53 lines (43 loc) · 1.18 KB
/
can_partition_bf.py
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
44
45
46
47
48
49
50
51
52
53
import collections
from typing import List
tests = {
1: [1,5,11,5],
2: [1,2,3,5],
3: [1, 1, 5, 7],
4: [1, 2, 5],
5: [1, 4, 5]
}
res = {
1: True,
2: False,
3: True,
4: False,
5: True
}
def check_result(index: int, output: bool):
if index > len(tests):
raise RuntimeError(f'Failed to get {index}th case')
return res.get(index, False) == output
def canPartition(nums: List[int]) -> bool:
if sum(nums) % 2 != 0:
return False
def canPartitionRec(nums: List[int], s, index):
if s == 0:
return True
if index >= len(nums):
return False
if s - nums[index] >= 0:
if canPartitionRec(nums, s - nums[index],
index + 1):
return True
return canPartitionRec(nums, s, index + 1)
return canPartitionRec(nums, int(sum(nums)/2), 0)
def main():
for index, input_list in tests.items():
res = canPartition(input_list)
if check_result(index, res):
print(f'Test case {index} is correct: {res}')
else:
print(f'Test case {index} is failed: {res}')
if __name__ == '__main__':
main()