
- 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 split a set into equal sum sets where elements in first set are smaller than second in Python
Suppose we have a list of numbers called nums, we have to check whether we can divide the list into two groups A and B such that: The sum of A and the sum of B are same. Here every number in A is strictly smaller than every number in B.
So, if the input is like nums = [3, 4, 5, 12], then the output will be True, as we can have A = [3,4,5] and B = [12] and both have sum 12.
To solve this, we will follow these steps −
sort the list nums
total := sum of all elements in nums
s := 0, i := 0
while i < size of nums, do
n := nums[i]
while i < size of nums and nums[i] is same as n, do
s := s + nums[i]
i := i + 1
if s is same as total − s, then
return True
return False
Let us see the following implementation to get better understanding −
Example
class Solution: def solve(self, nums): nums.sort() total = sum(nums) s = 0 i = 0 while i < len(nums): n = nums[i] while i < len(nums) and nums[i] == n: s += nums[i] i += 1 if s == total - s: return True return False ob = Solution() nums = [3, 4, 5, 12] print(ob.solve(nums))
Input
[3, 4, 5, 12]
Output
True
- Related Articles
- Program to find minimum length of first split of an array with smaller elements than other list in Python
- Program to find maximum sum of two sets where sums are equal in C++
- Swift Program to Split a set into Two Halves
- How to split a Dataset into Train sets and Test sets in Python?
- Breaking a Set into a list of sets using Python
- Python Program To Check Two Set Are Equal
- Python program to convert Set into Tuple and Tuple into Set
- Program to count non-empty subsets where sum of min and max element of set is less than k in Python
- Set the first array elements raised to powers from second array element-wise in Numpy
- Python Program to Extract Elements from a List in a Set
- Count elements smaller than or equal to x in a sorted matrix in C++
- Python program to find happiness by checking participation of elements into sets
- Convert set into a list in Python
- Split the array into equal sum parts according to given conditions in C++
- Program to group a set of points into k different groups in Python

Advertisements