
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 Can Be Divided Into Two Sub-Arrays With Absolute Difference in Python
Suppose, we are provided with an array "input_list" containing integer numbers. The problem given to us is to check if the given array can be divided into two halves, where the difference of the sum of two halves is equal to a number n. The number n will be provided beforehand.
So, if the input is like input_list= [9,2,5,6], n = 0, then the output will be “Possible”.
To solve this, we will follow these steps −
- list_total := sum of the values of input_list
- if (list_total - n) mod 2 is same as 1, then
- return "Not Possible"
- val := (list_total - n) / 2
- temp_sum := 0;
- for i in range 0 to size of input_list, do
- temp_sum := temp_sum + input_list[i]
- if temp_sum is same as val, then
- return "Possible"
- return "Not Possible"
Let us see the following implementation to get better understanding −
Example
def solve(input_list,n): list_total = sum(input_list) if (list_total - n) % 2 == 1: return "Not Possible" val = (list_total - n) / 2 temp_sum = 0; for i in range (0,len(input_list)): temp_sum += input_list[i] if (temp_sum == val): return "Possible" return "Not Possible" input_list= [9,2,5,6] n = 0 print(solve(input_list, n))
Input
[9,2,5,6], 0
Output
Possible
Advertisements