Python – Multisets – A class to count the elements of a set

Ok, so you probably have heard about set in Python – it is a collection with non-repeatable elements – as if you are a stamp collector and you need to collect only the unique stamps into your album. However, in order to obtain more unique stamps, you need to exchange the ones that you have more than once with other collectors. And this means that you need a multiset  – e.g. a set with elements that occur more than once and we are keeping a count of these.

This is how an empty swimming pool looks like.

So, let’s imagine that we are starting our collection with the following 3 stamps, repeated as follows:

  • Bulgarian history stamp – 5 times
  • Bulgarian post stamp – 10 times
  • Stamp with a Butterfly – 3 times

And after some time we get 5 times more stamps with a butterfly (cos they look cool!) and a new “Japanese history stamp”). The beauty of this is that we do not need to tell the multiset to calculate 5+3 = 8, but it does it on its own! Great stuff.

What is worth noticing is that we have two different functions, as follows:

  • len(stamp_collection)  – returning 4 – the total number of sets of stamps that we possess
  • sum(stamp_collection)  – returning 25 – the total number of stamps that we have

Enjoy! 🙂

Tagged with: , ,