Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to check whether we can make group of two partitions with equal sum or not in Python?
Suppose we have a list of numbers called nums, we have to check whether we can partition nums into two groups where the sum of the elements in both groups are the same.
So, if the input is like nums = [2, 3, 6, 5], then the output will be True, as we can make groups like: [2, 6] and [3, 5].
Algorithm
To solve this, we will follow these steps ?
total:= sum of all elements innums-
if
totalis odd, thenreturn
False
half:= integer part oftotal / 2dp:= a list of sizehalf + 1and fill withFalsedp[0]:=True-
for each
numinnums, do-
for
iin rangehalfto0, decrease by 1, do-
if
i >= num, thendp[i]:=dp[i]ORdp[i - num]
-
-
return
dp[half]
Example
Let's implement this algorithm to check if we can partition the list into two equal sum groups ?
class Solution:
def solve(self, nums):
total = sum(nums)
if total & 1:
return False
half = total // 2
dp = [True] + [False] * half
for num in nums:
for i in range(half, 0, -1):
if i >= num:
dp[i] |= dp[i - num]
return dp[half]
ob = Solution()
nums = [2, 3, 6, 5]
print(ob.solve(nums))
The output of the above code is ?
True
How It Works
This algorithm uses dynamic programming to solve the partition problem. First, we calculate the total sum and check if it's even (if odd, equal partition is impossible). Then we use a boolean array dp where dp[i] represents whether we can achieve sum i using the numbers processed so far. We iterate through each number and update the DP array backwards to avoid using the same number twice.
Example with Another Input
Let's test with a case where equal partition is not possible ?
ob = Solution()
nums = [1, 5, 11, 5]
print(f"Can partition {nums}: {ob.solve(nums)}")
nums2 = [1, 2, 3, 5]
print(f"Can partition {nums2}: {ob.solve(nums2)}")
The output of the above code is ?
Can partition [1, 5, 11, 5]: True Can partition [1, 2, 3, 5]: False
Conclusion
This dynamic programming approach efficiently determines if a list can be partitioned into two equal sum groups. The algorithm has O(n × sum) time complexity and works by checking if we can achieve exactly half of the total sum using available numbers.
