
- 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 the array has an element which is equal to sum of all the remaining elements in Python
Suppose we have an array called nums we have to check whether the array contains an element whose value is same as sum of all other elements.
So, if the input is like nums = [3,2,10,4,1], then the output will be True, 10 = (3+2+4+1).
To solve this, we will follow these steps −
- freq := an empty map
- total := 0
- for i in range 0 to size of nums - 1, do
- freq[nums[i]] := freq[nums[i]] + 1
- total := total + nums[i]
- if total is even, then
- if freq[quotient of (total / 2)] is non-zero, then
- return True
- if freq[quotient of (total / 2)] is non-zero, then
- return False
Let us see the following implementation to get better understanding −
Example Code
from collections import defaultdict def solve(nums): freq = defaultdict(int) total = 0 for i in range(len(nums)): freq[nums[i]] += 1 total += nums[i] if total % 2 == 0: if freq[total // 2]: return True return False nums = [3,2,10,4,1] print(solve(nums))
Input
[3,2,10,4,1]
Output
True
- Related Articles
- Check if the array has an element which is equal to product of remaining elements in Python
- Element equal to the sum of all the remaining elements in C++
- Check if an array contains all elements of a given range in Python
- Find if array has an element whose value is half of array sum in C++
- Check if all array elements are distinct in Python
- Check if all elements of the array are palindrome or not in Python
- Find an element in array such that sum of left array is equal to sum of right array using c++
- Check if some elements of array are equal JavaScript
- Check whether the sum of prime elements of the array is prime or not in Python
- Sum of all the non-repeating elements of an array JavaScript
- Check if an array object is equal to another array object in C#
- Number of operations required to make all array elements Equal in Python
- Find an element which divides the array in two subarrays with equal product in Python
- Check if elements of an array can be arranged satisfying the given condition in Python
- Check if an array of 1s and 2s can be divided into 2 parts with equal sum in Python

Advertisements