-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdailycoding060.py
58 lines (44 loc) · 1.4 KB
/
dailycoding060.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
54
55
56
57
"""
This problem was asked by Facebook.
Given a multiset of integers, return whether it can be partitioned into
two subsets whose sums are the same.
For example, given the multiset {15, 5, 20, 10, 35, 15, 10},
it would return true, since we can split it up into {15, 5, 10, 15, 10} and
{20, 35}, which both add up to 55.
Given the multiset {15, 5, 20, 10, 35}, it would return false,
since we can't split it up into two subsets that add up to the same sum.
Solution:
Sort the nums and greedily search for the sum // 2, if found, then return True.
Runs in O(n^2)
"""
def can_partition(nums):
if len(nums) == 0:
return False
tot, size = sum(nums), len(nums)
if tot % 2 == 1:
return False
# Sort the list in reverse and greedily search for the target
target = tot // 2
nums.sort(reverse=True)
for i in range(size):
temp = 0
for j in range(i, size):
if temp + nums[j] == target:
return True
elif temp + nums[j] < target:
temp += nums[j]
return False
def main():
tests = (
([15, 5, 20, 10, 35], False),
([15, 5, 20, 10, 35, 15, 10], True),
([10, 4], False),
([4, 1, 5], True),
([9, 3, 1], False)
)
if all(can_partition(k) == test for k, test in tests):
print("Passed")
else:
print("Failed")
if __name__ == '__main__':
main()