
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 Contains Element Equal to Sum of 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
Advertisements