- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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
- Related Articles
- Program to find three unique elements from list whose sum is closest to k Python
- Python program to find sum of elements in list
- Program to find length of longest consecutive sublist with unique elements in Python
- Find sum of elements in list in Python program
- Program to find sum of odd elements from list in Python
- Program to find the product of three elements when all are unique in Python
- Program to find sum of all elements of a tree in Python
- Program to check we can find three unique elements ose sum is same as k or not Python
- C program to find the unique elements in an array.
- Program to find largest sum of non-adjacent elements of a list in Python
- Finding sum of all unique elements in JavaScript
- Program to find sum of non-adjacent elements in a circular list in python
- Program to find a list of numbers where each K-sized window has unique elements in Python
- Program to count number of sublists with exactly k unique elements in Python
- Program to find maximum sum by flipping each row elements in Python

Advertisements