Working with math sets using Python

by Rafael Tavares


Warning: ksort() expects parameter 1 to be array, object given in /home/croozeus/public_html/blogs/wp-content/plugins/yet-another-related-posts-plugin/includes.php on line 256

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:

  1. OAuth, PyS60 and Twitter: now working ! Since August 31th Twitter is not supporting the old user/password...
  2. Python on Symbian: Mobile app development made easy We are pleased to announce the release of a new...
  3. 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.