Reputation: 245
I need help trying to sum up numbers in a list while ignoring duplicates. Let's say I have a list [1, 2, 2, 3, 3, 3] the answer should be 6 because 1 + 2 + 3 = 6. The extra 2 and extra 3s should not be included in the calculation.
def sumOfUniqueNums(list):
sum = 0
list1 = [1, 2, 2, 3, 3, 3]
remove = []
[remove.append(i) for i in list1 if i not in remove]
sum(list1)
return sum
def sumOfUniqueNums(numbers):
return sum(set(numbers))
Upvotes: 0
Views: 1553
Reputation: 77137
A set cannot contain duplicate values, so it's as simple as
sum(set(list1))
Python will let you override built-in names, though, so you'll need to unassign sum
before this will work.
Upvotes: 4
Reputation: 3554
Try this, should work fine:
def sumOfUniqueNums(values):
return sum(set(values))
print sumOfUniqueNums([1,1,2,2])
3
print sumOfUniqueNums([1,1,2,2,3])
6
Upvotes: 0