 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP 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
Program to 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
 