Search for identical numbers at the input and summing paired numbers

I want to find numerical pairs in the input, and then sum these pairs, but leave unpaired numbers. By this I mean

8 8 8 = 16
8 8 8 8 8 = 32

therefore, numbers with two of the two will be counted, but a number that does not have a pair will not be counted. Sorry if I phrased this weirdly, I don’t know how to explain it, but an example will help.

For example:

8 3 4 4 5 9 9 5 2

Output:

36

4 + 4 + 5 + 5 + 9 + 9 = 36

In Python.

+4
source share
2 answers

As a response correction, @ avinash-raj gave:

import collections
s = "8 3 4 4 5 9 9 5 2"
l = s.split()
print(sum([int(item) * 2 * (count // 2) for item, count in collections.Counter(l).items()]))

As an explanation:

  • we pick up all the numbers up to a Counterthat tell us the number of times the key was noticed

  • (count // 2) . , 9 , (count // 2)9 / 2 → 4.

+1

collections.Counter

>>> import collections
>>> s = "8 3 4 4 5 9 9 5 2"
>>> l = s.split()
>>> sum([int(item)*count for item, count in collections.Counter(l).items() if count > 1])
36

>>> s = "8 3 4 4 5 9 9 5 2"
>>> l = s.split()
>>> sum([int(item)*count for item, count in collections.Counter(l).items() if count%2 == 0])

36
+3

Source: https://habr.com/ru/post/1610068/


All Articles