Python language basics 53: basic set algebra operations cont’d

Introduction

In the previous post we looked at a 4 basic set operations from the world of set algebra: union, complement, intersection and symmetric difference. We saw how Python supported all 4 operations with convenient built-in functions.

In this post we’ll look at 3 other operations from set algebra that all return boolean results.

Boolean set algebra

Boolean set algebra tests for the presence of certain characteristics of two sets. The test will always return true or false. Let’s take a look at some of them.

Disjoint

Disjoint sets are sets that have no single element in common. Consider the following example:

set_a = {4, 6, 3, 5, 9, 8, 7}
set_b = {6, 5, 7, 1, 2}
is_disjoint = set_a.isdisjoint(set_b)

The isdisjoint method will return False as set_a and set_b have 3 elements in common – 5, 6 and 7 – and are therefore not disjoint sets. The following on the other hand will return True:

set_a = {4, 6, 3, 5, 9, 8, 7}
set_b = {1, 2}
is_disjoint = set_a.isdisjoint(set_b)

Subset and superset

We can discuss subsets and supersets in the same section as they are perfectly symmetric operations. Let’s see how Wikipedia defines them:

“…a set A is a subset of a set B, or equivalently B is a superset of A, if A is “contained” inside B, that is, all elements of A are also elements of B.”

Python has the ‘issubset’ and ‘issuperset’ methods to test for these conditions. Let’s see how issubset works:

set_a = {4, 6, 3, 5, 9, 8, 7}
set_b = {3, 5, 9}
is_subset = set_b.issubset(set_a)

As all elements in set_b are contained in set_a, set_b is indeed a subset of set_a and the function returns True. Conversely we’re expecting that set_a is a superset of set_b:

is_superset = set_a.issuperset(set_b)

Indeed, the function returns True.

Let’s see an example for the contrary:

set_a = {4, 6, 3, 5, 9, 8, 7}
set_b = {3, 5, 9, 1}
is_superset = set_a.issuperset(set_b)

The issuperset function returns False as set_b includes the element 1 which doesn’t appear in set_a.

In the next post we’ll discuss how to create a copy of a set.

Read all Python-related posts on this blog here.

Advertisement

About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

Once Upon a Camayoc

Bite-size insight on Cyber Security for the not too technical.

%d bloggers like this: