[Edu-sig] multiplying permutations

Andrzej Kapanowski ufkapano at gmail.com
Fri Mar 11 09:34:57 CET 2011


Hello!
Here is a useful class to handle permutations.
-----------------------------------------------------------------
class Perm:
    def __init__(self, size, cycle=None):
        self.size = size
        self.data = range(size)
        if cycle:
            n = len(cycle)
            for i in range(n):
                self.data[cycle[i]] = cycle[(i+1) % n]
    def __str__(self):
        return str(self.data)
    def __mul__(self, other):
        if self.size != other.size:
            print "error: different size"
            return
        tmp = Perm(self.size)
        for key in range(tmp.size):
            tmp.data[key] = self.data[other.data[key]]
        return tmp
    def __invert__(self):   #  ~p
        tmp = Perm(self.size)
        for i in range(tmp.size):
            tmp.data[self.data[i]] = i
        return tmp
-------------------------------------------------------------------------------------
# Exemplary calculations
N = 4

E = Perm(N)
R1 = Perm(N,(0,1)) * Perm(N,(2,3))
R2 = Perm(N,(0,2)) * Perm(N,(1,3))
R3 = R1 * R2
# {E, R1, R2, R3} form D_2 group

H = Perm(N,(0,1,3,2))
print H, ~H, H*(~H)
-------------------------------------------------------------------------
Regards,
Andrzej Kapanowski
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/edu-sig/attachments/20110311/0779aa5c/attachment.html>


More information about the Edu-sig mailing list