
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
Find Sum of Unique Elements in Python
Suppose we have an array nums with few duplicate elements and some unique elements. We have to find the sum of all the unique elements present in nums.
So, if the input is like nums = [5,2,1,5,3,1,3,8], then the output will be 10 because only unique elements are 8 and 2, so their sum is 10.
To solve this, we will follow these steps −
count := a dictionary holding all unique elements and their frequency
ans := 0
-
for each index i and value v in nums, do
-
if count[v] is same as 1, then
ans := ans + v
-
return ans
Example (Python)
Let us see the following implementation to get better understanding −
from collections import Counter def solve(nums): count = Counter(nums) ans = 0 for index,value in enumerate(nums): if count[value]==1: ans+=value return ans nums = [5,2,1,5,3,1,3,8] print(solve(nums))
Input
[5,2,1,5,3,1,3,8]
Output
10
Advertisements