
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Check If 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
Advertisements