Using Counter Instances As Multisets
In the previous two lessons, I showed some practical applications of the
Counter class. In this lesson, I’ll go a little bit mathy and show you how counters can be a special type of set—the multiset.
01:29 A set in math is a collection of things with unique members. Python has a built-in data type for handling sets. Here, I’ve just created one. Note how the multiple ones and fours end up having just a single instance in the set.
Now let’s try that with our favorite state … and the same idea, but this time the members are letters. There are cases in math where you want sets without the unique member restriction. Enter Python’s
Putting these factors together in a counter gives a multiset of the prime factors of eighty-five thousand. Having that in place, you can determine the resulting number using the
.elements() method. First, let me create a variable to store the result.
And with that done, you’ve got a
product variable containing the results. If you’re using Python 3.8 or greater, you can do this in even less code by using the
prod() function in the
The total sales for the two days can be found by adding the counters. Note that the
.subtract() method that I was showing you just before updates the
Counter object in place.
.addition() creates a new counter, combining the data stored in
day2 together into a third object.
Difference is also supported. The sales increment would be how much better you did on day two than day one. A couple things to notice here. Like addition, this is creating a new object. Don’t confuse the
.subtract() method with the
minus operator (
-). They both do subtraction, but have different effects.
06:05 The second thing to notice is how difference handles negative values. It ignores them. Day one has nine oranges. Day two has eight. The difference is a negative number, so it isn’t included at all.
06:18 This may or may not be the behavior you want. So be careful. You can combine multisets through both intersection and union operations. The intersection of two counters is the minimum values of the items in the two sets.
The tomatoes are gone. Doing the same thing with the unary minus (
-), and you get a new counter with only the negative values. But note that you’re getting a positive count of them. With a little clever coding, you could combine the idea of the unary plus and the unary minus and build your own subtraction that handled negative numbers without removing them.
Become a Member to join the conversation.