-3

how do i check how what is the duplicate numbers and what their sum? I am working on a project and I cant get it.

list = [1, 3, 5, 2, 1, 6, 5, 10, 1]

3 Answers3

0

You can iterate the list and count how many times each element is met, then it's easy to check which elements are repeated (they have counter greater than 1), and the sum would be simply element_value*count

li = [1, 3, 5, 2, 1, 6, 5, 10, 1]
counters = {}
for element in li:
    counters[element] = counters.get(element, 0) + 1

for element, count in counters.items():
    if count >= 2:
        print('Repeated element', element, 'sum=', element*count)
Alexey S. Larionov
  • 6,555
  • 1
  • 18
  • 37
0

You can set up a separate set to check which items have already been seen, and for those where this is the case you add them to a sum:

sum = 0
li = [1, 3, 5, 2, 1, 6, 5, 10, 1]
seen_numbers = set()
for n in li:
    if n not in seen_numbers:
        seen_numbers.add(n)
    else:
        sum += n

Note that this will add a number that is already in the list each time it recurs, i.e., a number that appears three times will be added to sum twice. I don't know if that's what you want.

Schnitte
  • 1,193
  • 4
  • 16
0

If you need the single results you can construct a list where each element is a tuple. Each tuple contains the number, the count and the sum.

from collections import Counter

data = [1, 3, 5, 2, 1, 6, 5, 10, 1]
result = [(value, count, value*count) for value, count in Counter(data).items() if count > 1]
print(result)

If you need to find only the full total of all values that appear more than once:

print(sum(value*count for value, count in Counter(data).items() if count > 1))
Matthias
  • 12,873
  • 6
  • 42
  • 48