
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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 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].
To solve this, we will follow these steps
total := sum of all elements in nums
if total is odd, then
return False
half := integer part of total / 2
dp := a list of size half + 1 and fill with false
dp[0] := true
for each num in nums, do
for i in range half to 0, decrease by 1, do
if i >= num, then
dp[i] := dp[i] OR dp[i - num]
return dp[half]
Example
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))
Input
[2, 3, 6, 5]
Output
True
- Related Articles
- Program to check whether we can partition a list with k-partitions of equal sum in C++
- Program to check whether one string swap can make strings equal or not using Python
- Program to check whether we can make k palindromes from given string characters or not in Python?
- Python program to check whether we can pile up cubes or not
- Program to check whether we can take all courses or not in Python
- Program to check whether we can unlock all rooms or not in python
- Golang Program to Check Whether Two Matrices are Equal or Not
- Swift Program to Check Whether Two Matrices Are Equal or Not
- Program to check whether we can get N queens solution or not in Python
- Program to check whether we can convert string in K moves or not using Python
- Program to check two strings can be equal by swapping characters or not in Python
- Program to check whether we can split list into consecutive increasing sublists or not in Python
- Program to check whether two sentences are similar or not in Python
- Program to check whether two trees can be formed by swapping nodes or not in Python
- Check whether two schedules are view equal or not(DBMS)

Advertisements