python - Finding the same numbers in an input and summing the paired numbers -


i want find number pairs in input, sum pairs, leave out unpaired numbers. mean

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

so numbers pair of 2 counted number doesn't have pair won't counted. sorry if worded weird don't know how explain it, example help.

for example:

8 3 4 4 5 9 9 5 2 

would output:

36 

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

in python.

as correction of answer @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) item, count in collections.counter(l).items()])) 

as explanation:

  • we vacuum numbers in counter, tell number of times key has been seen

  • the expression (count // 2) integer division, , gives number of complete pairs. if we've seen key 9 times, (count // 2) -> 9 / 2 -> 4.


Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -