In [4]:
from message import Message
from key import Key
import numpy as np
alpha = 'abcdefghijklmnopqrstuvwxyz'
message = Message(alpha)
key = np.array(range(26))
key[0] = 25
key[25] = 0

In [10]:
%%timeit
message.map1(key)


100000 loops, best of 3: 10.8 µs per loop

In [11]:
%%timeit
message.map2(key)


100000 loops, best of 3: 11.3 µs per loop

In [1]:
from message import Message
alpha = 'abcdefghijklmnopqrstuvwxyz'
my_message = Message(alpha)

In [6]:
%%timeit
my_message.frequencies(alpha)


The slowest run took 5.76 times longer than the fastest. This could mean that an intermediate result is being cached 
100000 loops, best of 3: 12 µs per loop

In [21]:
from message import Message
from key import Key
import numpy as np
with open('sample.txt','r') as source:
    text = source.read()
my_message = Message(text)
my_message = my_message.filter()
encipher_key = Key()
encipher_key.random_key()
enciphered_message = my_message.map(encipher_key)
enciphered_message.text
decipher_key = encipher_key.invert()
deciphered_message = enciphered_message.map(decipher_key)
#deciphered_message.text


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-21-b71e81a674f1> in <module>()
     11 enciphered_message.text
     12 decipher_key = encipher_key.invert()
---> 13 deciphered_message = enciphered_message.map(decipher_key)
     14 #deciphered_message.text

C:\Users\Paul Brookes\Documents\GitHub\subcipher\message.pyc in map(self, key)
     13                 new_message += x
     14             else:
---> 15                 mapped_to = self.alpha[key.map[x_index]]
     16                 new_message += mapped_to
     17         return Message(new_message)

TypeError: string indices must be integers, not numpy.float64

In [22]:
decipher_key.map


Out[22]:
array([  4.,   5.,  12.,   6.,   0.,  18.,  16.,  24.,  21.,   9.,  23.,
        25.,  22.,  14.,   8.,   7.,  11.,  17.,  20.,  13.,  10.,   3.,
         1.,  19.,  15.,  26.,   2.])

In [1]:
import numpy as np
import random
default_alpha = 'abcdefghijklmnopqrstuvwxyz '

class Key(object):
    def __init__(self, map=[]):
        self.map = map

    def substitute(self, new_map):
        map_out = np.zeros(self.map.shape[0])
        for x in range(self.map.shape[0]):
            map_out[x] = new_map[self.map[x]]
        return Key(map_out)

    def invert(self):
        inverted_map = np.zeros(self.map.shape[0])
        for x in range(self.map.shape[0]):
            inverted_map[self.map[x]] = x
        return Key(inverted_map)

    def obtain_key(self, alpha, beta):
        key = np.zeros(len(beta))
        for x in range(len(beta)):
            key[x] = alpha.find(beta[x])
        return Key(key)

    def random_key(self, alpha = default_alpha):
        self.map = np.array(range(len(alpha)))
        random.shuffle(self.map)
        
key = Key(np.array([1,2,0]))
inverted_key = key.invert()
inverted_key.map


Out[1]:
array([ 2.,  0.,  1.])

In [26]:
import numpy as np

class Message(object):
    def __init__(self, text, alpha = 'abcdefghijklmnopqrstuvwxyz '):
        self.text = text
        self.alpha = alpha

    def map(self, key):
        new_message = ''
        for x in self.text:
            x_index = self.alpha.find(x)
            if x_index == -1:
                new_message += x
            else:
                mapped_to = self.alpha[key.map[x_index]]
                new_message += mapped_to
        return Message(new_message)

    def frequencies(self, alpha = 0):
        if alpha == 0:
            alpha = self.alpha
        counts = np.zeros([len(alpha)])
        for i, x in enumerate(alpha):
            counts[i] = self.text.count(x)
        rates = counts/len(self.text)
        return rates

    def filter(self, alpha = 0):
        if alpha == 0:
            alpha = self.alpha
        filtered_message = ''
        for x in self.text.lower():
            if x in alpha:
                filtered_message += x
        return Message(filtered_message, self.alpha)

    

from key import Key
import numpy as np
with open('sample.txt','r') as source:
    text = source.read()
my_message = Message(text)
my_message = my_message.filter()
#encipher_key = Key()
#encipher_key.random_key()
map = np.array(range(27))
encipher_key = Key(map)
enciphered_message = my_message.map(encipher_key)
enciphered_message.text
decipher_key = encipher_key.invert()
deciphered_message = enciphered_message.map(decipher_key)
deciphered_message.text


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-26-95faf01a906e> in <module>()
     50 enciphered_message.text
     51 decipher_key = encipher_key.invert()
---> 52 deciphered_message = enciphered_message.map(decipher_key)
     53 deciphered_message.text

<ipython-input-26-95faf01a906e> in map(self, key)
     13                 new_message += x
     14             else:
---> 15                 mapped_to = self.alpha[key.map[x_index]]
     16                 new_message += mapped_to
     17         return Message(new_message)

TypeError: string indices must be integers, not numpy.float64

In [44]:
import numpy as np

class Message(object):
    def __init__(self, text, alpha = 'abcdefghijklmnopqrstuvwxyz '):
        self.text = text
        self.alpha = alpha

    def map(self, key):
        new_message = ''
        for x in self.text:
            x_index = self.alpha.find(x)
            if x_index == -1:
                new_message += x
            else:
                mapped_to = self.alpha[key.map[x_index]]
                new_message += mapped_to
        return Message(new_message)

    def frequencies(self, alpha = 0):
        if alpha == 0:
            alpha = self.alpha
        counts = np.zeros([len(alpha)])
        for i, x in enumerate(alpha):
            counts[i] = self.text.count(x)
        rates = counts/len(self.text)
        return rates

    def filter(self, alpha = 0):
        if alpha == 0:
            alpha = self.alpha
        filtered_message = ''
        for x in self.text.lower():
            if x in alpha:
                filtered_message += x
        return Message(filtered_message, self.alpha)

    

from key import Key
import numpy as np
with open('sample.txt','r') as source:
    text = source.read()
my_message = Message(text)
my_message = my_message.filter()

encipher_key = Key()
encipher_key.random_key()

enciphered_message = my_message.map(encipher_key)
enciphered_message.text
decipher_key = encipher_key.invert()
deciphered_message = enciphered_message.map(decipher_key)
deciphered_message.text


Out[44]:
'the morning had dawned clear and cold with a crispness that hinted at the end of summer they set forth at daybreak to see a man beheaded twenty in all and bran rode among them nervous with excitement this was the first time he had been deemed old enough to go with his lord father and his brothers to see the kings justice done it was the ninth year of summer and the seventh of brans lifethe man had been taken outside a small holdfast in the hills robb thought he was a wildling his sword sworn to mance rayder the kingbeyondthewall it made brans skin prickle to think of it he remembered the hearth tales old nan told them the wildlings were cruel men she said slavers and slayers and thieves they consorted with giants and ghouls stole girl children in the dead of night and drank blood from polished horns and their women lay with the others in the long night to sire terrible halfhuman childrenbut the man they found bound hand and foot to the holdfast wall awaiting the kings justice was old and scrawny not much taller than robb he had lost both ears and a finger to frostbite and he dressed all in black the same as a brother of the nights watch except that his furs were ragged and greasythe breath of man and horse mingled steaming in the cold morning air as his lord father had the man cut down from the wall and dragged before them robb and jon sat tall and still on their horses with bran between them on his pony trying to seem older than seven trying to pretend that hed seen all this before a faint wind blew through the holdfast gate over their heads flapped the banner of the starks of winterfell a grey direwolf racing across an icewhite fieldbrans father sat solemnly on his horse long brown hair stirring in the wind his closely trimmed beard was shot with white making him look older than his thirtyfive years he had a grim cast to his grey eyes this day and he seemed not at all the man who would sit before the fire in the evening and talk softly of the age of heroes and the children of the forest he had taken off fathers face bran thought and donned the face of lord stark of winterfellthere were questions asked and answers given there in the chill of morning but afterward bran could not recall much of what had been said finally his lord father gave a command and two of his guardsmen dragged the ragged man to the ironwood stump in the center of the square they forced his head down onto the hard black wood lord eddard stark dismounted and his ward theon greyjoy brought forth the sword ice that sword was called it was as wide across as a mans hand and taller even than robb the blade was valyrian steel spellforged and dark as smoke nothing held an edge like valyrian steelhis father peeled off his gloves and handed them to jory cassel the captain of his household guard he took hold of ice with both hands and said in the name of robert of the house baratheon the first of his name king of the andals and the rhoynar and the first men lord of the seven kingdoms and protector of the realm by the word of eddard of the house stark lord of winterfell and warden of the north i do sentence you to die he lifted the greatsword high above his headbrans bastard brother jon snow moved closer keep the pony well in hand he whispered and dont look away father will know if you dobran kept his pony well in hand and did not look awayhis father took off the mans head with a single sure stroke blood sprayed out across the snow as red as surnmerwine one of the horses reared and had to be restrained to keep from bolting bran could not take his eyes off the blood the snows around the stump drank it eagerly reddening as he watchedthe head bounced off a thick root and rolled it came up near greyjoys feet theon was a lean dark youth of nineteen who found everything amusing he laughed put his boot on the head and kicked it awayass jon muttered low enough so greyjoy did not hear he put a hand on brans shoulder and bran looked over at his bastard brother you did well jon told him solemnly jon was fourteen an old hand at justiceit seemed colder on the long ride back to winterfell though the wind had died by then and the sun was higher in the sky bran rode with his brothers well ahead of the main party his pony struggling hard to keep up with their horsesthe deserter died bravely robb said he was big and broad and growing every day with his mothers coloring the fair skin redbrown hair and blue eyes of the tullys of riverrun he had courage at the leastno jon snow said quietly it was not courage this one was dead of fear you could see it in his eyes stark jons eyes were a grey so dark they seemed almost black but there was little they did not see he was of an age with robb but they did not look alike jon was slender where robb was muscular dark where robb was fair graceful and quick where his half brother was strong and fastrobb was not impressed the others take his eyes he swore he died well race you to the bridgedone jon said kicking his horse forward robb cursed and followed and they galloped off down the trail robb laughing and hooting jon silent and intent the hooves of their horses kicked up showers of snow as they wentbran did not try to follow his pony could not keep up he had seen the ragged mans eyes and he was thinking of them now after a while the sound of robbs laughter receded and the woods grew silent againso deep in thought was he that he never heard the rest of the party until his father moved up to ride beside him are you well bran he asked not unkindlyyes father bran told him he looked up wrapped in his furs and leathers mounted on his great warhorse his lord father loomed over him like a giant robb says the man died bravely but jon says he was afraidwhat do you think his father askedbran thought about it can a man still be brave if hes afraidthat is the only time a man can be brave his father told him do you understand why i did ithe was a wildling bran said they carry off women and sell them to the othershis lord father smiled old nan has been telling you stories again in truth the man was an oathbreaker a deserter from the nights watch no man is more dangerous the deserter knows his life is forfeit if he is taken so he will not flinch from any crime no matter how vile but you mistake me the question was not why the man had to die but why i must do itbran had no answer for that king robert has a headsman he said uncertainlyhe does his father admitted as did the targaryen kings before him yet our way is the older way the blood of the first men still flows in the veins of the starks and we hold to the belief that the man who passes the sentence should swing the sword if you would take a mans life you owe it to him to look into his eyes and hear his final words and if you cannot bear to do that then perhaps the man does not deserve to dieone day bran you will be robbs bannerman holding a keep of your own for your brother and your king and justice will fall to you when that day comes you must take no pleasure in the task but neither must you look away a ruler who hides behind paid executioners soon forgets what death isthat was when jon reappeared on the crest of the hill before them he waved and shouted down at them father bran come quickly see what robb has found then he was gone againjory rode up beside them trouble my lordbeyond a doubt his lord father said come let us see what mischief my sons have rooted out now he sent his horse into a trot jory and bran and the rest came afterthey found robb on the riverbank north of the bridge with jon still mounted beside him the late summer snows had been heavy this moonturn robb stood kneedeep in white his hood pulled back so the sun shone in his hair he was cradling something in his arm while the boys talked in hushed excited voicesthe riders picked their way carefully through the drifts groping for solid footing on the hidden uneven ground jory cassel and theon greyjoy were the first to reach the boys greyjoy was laughing and joking as he rode bran heard the breath go out of him gods he exclaimed struggling to keep control of his horse as he reached for his swordjorys sword was already out robb get away from it he called as his horse reared under himrobb grinned and looked up from the bundle in his arms she cant hurt you he said shes dead jorybran was afire with curiosity by then he would have spurred the pony faster but his father made them dismount beside the bridge and approach on foot bran jumped off and ranby then jon jory and theon greyjoy had all dismounted as well what in the seven hells is it greyjoy was sayinga wolf robb told hima freak greyjoy said look at the size of itbrans heart was thumping in his chest as he pushed through a waisthigh drift to his brothers sidehalfburied in bloodstained snow a huge dark shape slumped in death ice had formed in its shaggy grey fur and the faint smell of corruption clung to it like a womans perfume bran glimpsed blind eyes crawling with maggots a wide mouth full of yellowed teeth but it was the size of it that made him gasp it was bigger than his pony twice the size of the largest hound in his fathers kennelits no freak jon said calmly thats a direwolf they grow larger than the other kindtheon greyjoy said theres not been a direwolf sighted south of the wall in two hundred yearsi see one now jon repliedbran tore his eyes away from the monster that was when he noticed the bundle in robbs arms he gave a cry of delight and moved closer the pup was a tiny ball of greyblack fur its eyes still closed it nuzzled blindly against robbs chest as he cradled it searching for milk among his leathers making a sad little whimpery sound bran reached out hesitantly go on robb told him you can touch himbran gave the pup a quick nervous stroke then turned as jon said here you go his half brother put a second pup into his arms there are five of them bran sat down in the snow and hugged the wolf pup to his face its fur was soft and warm against his cheekdirewolves loose in the realm after so many years muttered hullen the master of horse i like it notit is a sign jory saidfather frowned this is only a dead animal jory he said yet he seemed troubled snow crunched under his boots as he moved around the body do we know what killed hertheres something in the throat robb told him proud to have found the answer before his father even asked there just under the jawhis father knelt and groped under the beasts head with his hand he gave a yank and held it up for all to see a foot of shattered antler tines snapped off all wet with blooda sudden silence descended over the party the men looked at the antler uneasily and no one dared to speak even bran could sense their fear though he did not understandhis father tossed the antler to the side and cleansed his hands in the snow im surprised she lived long enough to whelp he said his voice broke the spellmaybe she didnt jory said ive heard tales    maybe the bitch was already dead when the pups cameborn with the dead another man put in worse luckno matter said hullen they be dead soon enough toobran gave a wordless cry of dismaythe sooner the better theon greyjoy agreed he drew his sword give the beast here branthe little thing squirmed against him as if it heard and understood no bran cried out fiercely its mineput away your sword greyjoy robb said for a moment he sounded as commanding as their father like the lord he would someday be we will keep these pupsyou cannot do that boy said harwin who was hullens sonit be a mercy to kill them hullen saidbran looked to his lord father for rescue but got only a frown a furrowed brow hullen speaks truly son better a swift death than a hard one from cold and starvationno he could feel tears welling in his eyes and he looked away he did not want to cry in front of his fatherrobb resisted stubbornly ser rodriks red bitch whelped again last week he said it was a small litter only two live pups shell have milk enoughshell rip them apart when they try to nurselord stark jon said it was strange to hear him call father that so formal bran looked at him with desperate hope there are five pups he told father three male two femalewhat of it jonyou have five trueborn children jon said three sons two daughters the direwolf is the sigil of your house your children were meant to have these pups my lordbran saw his fathers face change saw the other men exchange glances he loved jon with all his heart at that moment even at seven bran understood what his brother had done the count had come right only because jon had omitted himself he had included the girls included even rickon the baby but not the bastard who bore the surname snow the name that custom decreed be given to all those in the north unlucky enough to be born with no name of their owntheir father understood as well you want no pup for yourself jon he asked softlythe direwolf graces the banners of house stark jon pointed out i am no stark fathertheir lord father regarded jon thoughtfully robb rushed into the silence he left i will nurse him myself father he promised i will soak a towel with warm milk and give him suck from thatme too bran echoedthe lord weighed his sons long and carefully with his eyes easy to say and harder to do i will not have you wasting the servants time with this if you want these pups you will feed them yourselves is that understoodbran nodded eagerly the pup squirmed in his grasp licked at his face with a warm tongueyou must train them as well their father said you must train them the kennelmaster will have nothing to do with these monsters i promise you that and the gods help you if you neglect them or brutalize them or train them badly these are not dogs to beg for treats and slink off at a kick a direwolf will rip a mans arm off his shoulder as easily as a dog will kill a rat are you sure you want thisyes father bran saidyes robb agreedthe pups may die anyway despite all you dothey wont die robb said we wont let them diekeep them then jory desmond gather up the other pups its time we were back to winterfellit was not until they were mounted and on their way that bran allowed himself to taste the sweet air of victory by then his pup was snuggled inside his leathers warm against him safe for the long ride home bran was wondering what to name himhalfway across the bridge jon pulled up suddenlywhat is it jon their lord father askedcant you hear itbran could hear the wind in the trees the clatter of their hooves on the ironwood planks the whimpering of his hungry pup but jon was listening to something elsethere jon said he swung his horse around and galloped back across the bridge they watched him dismount where the direwolf lay dead in the snow watched him kneel a moment later he was riding back to them smilinghe must have crawled away from the others jon saidor been driven away their father said looking at the sixth pup his fur was white where the rest of the litter was grey his eyes were as red as the blood of the ragged man who had died that morning bran thought it curious that this pup alone would have opened his eyes while the others were still blindan albino theon greyjoy said with wry amusement this one will die even faster than the othersjon snow gave his fathers ward a long chilling look i think not greyjoy he said this one belongs to me'

In [66]:
import numpy as np
import random
default_alpha = 'abcdefghijklmnopqrstuvwxyz '

class Key(object):
    def __init__(self, map=[]):
        self.map = map

    def substitute(self, new_map):
        map_out = np.zeros(self.map.shape[0])
        for x in range(self.map.shape[0]):
            map_out[x] = new_map[self.map[x]]
        return Key(map_out)

    def invert(self):
        inverted_map = np.zeros(self.map.shape[0], dtype = np.int8)
        for x in range(self.map.size):
            inverted_map[self.map[x]] = x
        return Key(inverted_map)

    def obtain_key(self, alpha, beta):
        key = np.zeros(len(beta))
        for x in range(len(beta)):
            key[x] = alpha.find(beta[x])
        return Key(key)

    def random_key(self, alpha = default_alpha):
        self.map = np.array(range(len(alpha)))
        random.shuffle(self.map)

    def frequency_key(self, natural_frequencies, observed_frequencies):
        natural_indices_sorted = np.argsort(natural_frequencies)
        observed_indices_sorted = np.argsort(observed_frequencies)
        frequency_key = np.zeros(natural_frequencies.size, dtype = np.int8)
        for i, x in enumerate(natural_indices_sorted):
            frequency_key[x] = observed_indices_sorted[i]
        return Key(frequency_key)

    def frequency_key2(self, natural_frequencies, observed_frequencies):
        natural_indices_sorted = np.argsort(natural_frequencies)
        observed_indices_sorted = np.argsort(observed_frequencies)
        frequency_key = np.zeros(natural_frequencies.size, dtype = np.int8)
        for x in range(frequency_key.size):
            frequency_key[natural_indices_sorted[i]] = observed_indices_sorted[i]
        return Key(frequency_key)
    
key = Key()
new_key=key.frequency_key(frequencies,frequencies)

In [68]:
key = Key()

In [73]:
%%timeit
new_key=key.frequency_key(frequencies,frequencies)


The slowest run took 12.50 times longer than the fastest. This could mean that an intermediate result is being cached 
100000 loops, best of 3: 12 µs per loop

In [72]:
%%timeit
new_key=key.frequency_key2(frequencies,frequencies)


100000 loops, best of 3: 13.7 µs per loop

In [59]:
np.zeros(3)


Out[59]:
array([ 0.,  0.,  0.])

In [60]:
a


Out[60]:
array([0, 1, 2, 3])

In [62]:
a = np.array([1,3,2])
for x, i in enumerate(a):
    print x, i


0 1
1 3
2 2

In [ ]: