Python Programming Challenge – Counting Pairs

Here’s a fun algorithmic challenge for you.

Given a list of integers, write a function to find the total number of complete pairs contained in the list.

For example: for the input

[3, 1, 2, 3, 1, 2],

the return value should be


because there are 2 1s, 2 2s and 2 3s.

4 has no matching pair.

The image above gives a visual representation of the problem.

Have a go now at the challenge. Here’s a function stub and some assertions to get you started. If you are not familiar with assert in Python, these are just basic tests which will raise errors if they are incorrect. If you run you code and get no AssertionErrors, it means all the tests passed and your code is correct.

Counting Pairs Python Coding Challenge

Counting Pairs Python Coding Challenge

How did you get on?

Click below to see my initial solution to this problem. Then I will show you some alternatives and refinements.

The approach in the above solution was to build a dictionary of frequencies for each unique item in the list, and then to use integer division (//) by 2 to then find how many complete pairs there were for each key. This works because, for example,

Python Counter

The creation of the frequencies dictionary in the above solution can be simplified by the of of a Counter from the Python collections module. This is handy little tool that it is well worth knowing about. You will need to import it to make use of it.

Solving the Python Counting Pairs Programming Challenge using Sets

Another approach you can use for this problem is the make use of sets. You can learn more about Python sets here. The basic idea is that a set is created from the list of items, which contains only a singe instance of each value in the list. It is then a simple matter to count the number of items corresponding to each set elements within the original list.

For a super-succinct verions of the above soluiton, you can do this:

There it is folks. I hope you had a good attempt at this Python programming challenge, and wheter you managed to solve it yourself or not, you learned something on the way.

Happy computing.

 Take your Python skills to the next level!

with our free email course on object oriented programming with Python