[Edu-sig] multiplying permutations

Kirby Urner kurner at oreillyschool.com
Fri Mar 11 00:43:21 CET 2011


"""
Source code for math-teach post
by Kirby Urner / OST
(c) GNU Public License, 2011
"""

import string, random

charset = list(string.ascii_lowercase + " ")

def make_perm( ):
    "make some random permutation object mapping " ",a-z into itself"

    target = charset[:] # copy all
    random.shuffle(target)  # in place reordering
    return Pobject(dict( zip(charset, target)))

class Pobject:
    """
    permutation objects are instantiated with a dict.  they
    may be multiplied and/or inverted
    """

    def __init__(self, perm):
        self.perm = perm

    def encrypt(self, plaintext):
        e = ''
        for char in plaintext:
            e += self.perm[char]
        return e

    def decrypt(self, ciphertext):
        e = ''
        inv = ~self # invert the permutation
        return inv.encrypt(ciphertext)

    def __invert__(self):
        invdict = {}
        for char in self.perm:
            invdict[self.perm[char]] = char
        return Pobject(invdict)

    def __mul__(self, other):
        output = {}
        for char in self.perm:
            output[char] = other.perm[self.perm[char]]
        return Pobject(output)

    def __repr__(self, abbrev = False):
        return str(sorted(self.perm.items(), key=lambda t: t[0]))


More information about the Edu-sig mailing list