### Working with math sets using Python

#### by Rafael Tavares

I always try to bring what I learn into programming, specially in math. So, as this year is my first on high school, we started learning math sets. In the exact moment my teacher was teaching it to us, I thought it could be easily implemented using Python. This is really easy to do in paper, but it might be useful for you while developing something else. Well, I got only few minutes to work on it, so I’ll present here only the operations (Union, Intersection and Difference).

Let’s start, then:

**1. Union**

def union(a,b): for x in a: for i in range(len(b)): for g in b: if x == g: b.pop(i) c = a + b c.sort() return c

**Example of usage:**

>>> a = [1,2,3] >>> b = [2,3,4] >>> print union(a,b) [1, 2, 3, 4]

As you can see, if A and B have any element in common, the final set will only append the element once, following the theory that says a set can’t have more than one element with the same value.

**2. Intersection**

The intersection operation returns a set containing the common values in A and B.

def intersection(a,b): c = [] for x in a: if x in b: c.append(x) if c == []: return "{ }" c.sort() return c

**Example of usage:**

>>> a = [3,4,5,6] >>> b = [3,6,7,8] >>> print intersection(a,b) [3, 6]

## 3. Difference

The difference between two sets are the exclusive elements of the first set.

def difference(a,b): c = [] for x in a: if x not in b: c.append(x) if c == []: return "{ }" c.sort() return c

**Example of usage:**

>>> a = [2,5,6,8] >>> b = [5,4,9,1] >>> print difference(a,b) [2, 6, 8]

If someone doesn’t understand the short explanations, please leave your question here. It will be my pleasure to answer it!

Hope you enjoy!

Related posts:

- OAuth, PyS60 and Twitter: now working ! Since August 31th Twitter is not supporting the old user/password...
- Python on Symbian: Mobile app development made easy We are pleased to announce the release of a new...
- A simple Progressbar implementation in Python A quick post just to share a small class to...

Related posts brought to you by Yet Another Related Posts Plugin.

Missed commenting on this one ðŸ™‚

This is quite a good article for math operations, Good one!

–Croozeus, who feels he should return to blogging this week ðŸ™‚

This is already implemented in python:

>>> x = set()

>>> y = set()

>>> x.add(1)

>>> x.add(2)

>>> x.add(3)

>>> y.add(2)

>>> y.add(3)

>>> y.add(4)

>>> x

set([1, 2, 3])

>>> y

set([2, 3, 4])

>>> x.union(y)

set([1, 2, 3, 4])

>>> x.intersection(y)

set([2, 3])

Hi Harry,

Very nice!

Didn’t knew that … thanks for showing!

BR,

Rafael.