
- 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
Check if an array of 1s and 2s can be divided into 2 parts with equal sum in Python
Suppose we have an array nums which only stores 1 and 2 in it. We have to check whether the array can be divided into two different parts such that sum of elements in each part is same.
So, if the input is like nums = [1, 1, 2, 2, 2], then the output will be True as we can divide this array like [1, 1, 2] and [2, 2] the sum of each part is 4.
To solve this, we will follow these steps −
- total := 0, one_count := 0
- total := sum of all elements of nums
- one_count := count of 1s in nums
- if total is even, then
- return False
- if integer part of (total / 2) is even, then
- return True
- if one_count > 0, then
- return True
- otherwise,
- return False
Let us see the following implementation to get better understanding −
Example
def solve(nums): total = 0 one_count = 0 total = sum(nums) one_count = nums.count(1) if total % 2: return False if (total // 2) % 2 == 0: return True if one_count > 0: return True else: return False nums = [1, 1, 2, 2, 2] print(solve(nums))
Input
[1, 1, 2, 2, 2]
Output
True
- Related Articles
- Check if any square (with one colored cell) can be divided into two equal parts in Python
- Find if array can be divided into two subarrays of equal sum in C++
- Check if an array can be divided into pairs whose sum is divisible by k in Python
- Find the sums for which an array can be divided into subarrays of equal sum in Python
- Partition Array Into Three Parts With Equal Sum in Python
- Check if a large number can be divided into two or more segments of equal sum in C++
- Can array be divided into n partitions with equal sums in JavaScript
- Count Substrings with equal number of 0s, 1s and 2s in C++
- Check if a sorted array can be divided in pairs whose sum is k in Python
- Check if array can be divided into two sub-arrays such that their absolute difference is Ks in Python
- Minimum Cuts can be made in the Chessboard such that it is not divided into 2 parts in Python
- Check if array can be sorted with one swap in Python
- Check if elements of array can be made equal by multiplying given prime numbers in Python
- Minimum Cuts can be made in the Chessboard such that it is not divided into 2 parts in C++
- Split the array into equal sum parts according to given conditions in C++

Advertisements