Added a text packing function
authorNeil Smith <neil.git@njae.me.uk>
Fri, 3 Nov 2017 08:48:28 +0000 (08:48 +0000)
committerNeil Smith <neil.git@njae.me.uk>
Fri, 3 Nov 2017 08:48:28 +0000 (08:48 +0000)
2017/2017-challenge4.ipynb

index 635f4518106147127cb705f95da1165419723dba..d500a15798c4ec6f3d8f1a2b374d76fc6038b217 100644 (file)
@@ -2,7 +2,7 @@
  "cells": [
   {
    "cell_type": "code",
-   "execution_count": 2,
+   "execution_count": 19,
    "metadata": {},
    "outputs": [],
    "source": [
   },
   {
    "cell_type": "code",
-   "execution_count": 18,
+   "execution_count": 41,
+   "metadata": {},
+   "outputs": [],
+   "source": [
+    "def tpack(text, width=100):\n",
+    "    lines = [text[0]]\n",
+    "    for word in text[1:]:\n",
+    "        if len(lines[-1]) + 1 + len(word) <= width:\n",
+    "            lines[-1] += (' ' + word)\n",
+    "        else:\n",
+    "            lines += [word]\n",
+    "    return lines"
+   ]
+  },
+  {
+   "cell_type": "code",
+   "execution_count": 20,
    "metadata": {},
    "outputs": [
     {
@@ -52,7 +68,7 @@
   },
   {
    "cell_type": "code",
-   "execution_count": 10,
+   "execution_count": 21,
    "metadata": {},
    "outputs": [
     {
@@ -61,7 +77,7 @@
        "(('comportment', <KeywordWrapAlphabet.from_largest: 3>), -2417.7329224996606)"
       ]
      },
-     "execution_count": 10,
+     "execution_count": 21,
      "metadata": {},
      "output_type": "execute_result"
     }
@@ -73,7 +89,7 @@
   },
   {
    "cell_type": "code",
-   "execution_count": 12,
+   "execution_count": 22,
    "metadata": {},
    "outputs": [
     {
   },
   {
    "cell_type": "code",
-   "execution_count": 121,
-   "metadata": {},
-   "outputs": [
-    {
-     "data": {
-      "text/plain": [
-       "2163"
-      ]
-     },
-     "execution_count": 121,
-     "metadata": {},
-     "output_type": "execute_result"
-    }
-   ],
-   "source": [
-    "open('4a.plaintext', 'w').write(affine_decipher(ca, m_a, a_a, o_a))"
-   ]
-  },
-  {
-   "cell_type": "code",
-   "execution_count": 13,
+   "execution_count": 23,
    "metadata": {},
    "outputs": [
     {
        "         'z': 61})"
       ]
      },
-     "execution_count": 13,
+     "execution_count": 23,
      "metadata": {},
      "output_type": "execute_result"
     }
   },
   {
    "cell_type": "code",
-   "execution_count": 14,
+   "execution_count": 24,
    "metadata": {
     "scrolled": true
    },
        "'etoainhsrdlumwycfgpbvkxjqz'"
       ]
      },
-     "execution_count": 14,
+     "execution_count": 24,
      "metadata": {},
      "output_type": "execute_result"
     }
   },
   {
    "cell_type": "code",
-   "execution_count": 15,
+   "execution_count": 25,
    "metadata": {},
    "outputs": [
     {
        " 's']"
       ]
      },
-     "execution_count": 15,
+     "execution_count": 25,
      "metadata": {},
      "output_type": "execute_result"
     }
   },
   {
    "cell_type": "code",
-   "execution_count": 16,
+   "execution_count": 26,
    "metadata": {},
    "outputs": [
     {
        "24"
       ]
      },
-     "execution_count": 16,
+     "execution_count": 26,
      "metadata": {},
      "output_type": "execute_result"
     }
   },
   {
    "cell_type": "code",
-   "execution_count": 27,
+   "execution_count": 43,
    "metadata": {},
    "outputs": [
     {
        " 'Z': 'u'}"
       ]
      },
-     "execution_count": 27,
+     "execution_count": 43,
      "metadata": {},
      "output_type": "execute_result"
     }
   },
   {
    "cell_type": "code",
-   "execution_count": 60,
+   "execution_count": 44,
+   "metadata": {},
+   "outputs": [
+    {
+     "name": "stdout",
+     "output_type": "stream",
+     "text": [
+      "nirrg,\n",
+      "\n",
+      "wirgiw smccested a cet ah tomun is fe heed i uomraer ihd sne tnomcnt gom wacnt pe ahterested ah joahahc ms. ner somrues nike uohyarwed tnit tne poov as peahc nmhted pg ih allecil ymhdriasahc cromb hiwed wadis fnaun nis peeh issouaited fatn sekeril terror hetforvs ah tne list yef geirs. wirgiw nis trikelled to astihpml yollofahc i leid oh tne pmger ah tne nobe fe uih suire tnew oyy, pmt ay tnit doesh’t forv tneh fe fall heed to yahd tne rest oy tne poov unibters peyore wadis do. fe ire potn nobahc gomr dairg as uleir, peuimse ay a iw racnt fe fall nike ihotner tnree bliues to kasat iyter tnas ohe, ihd a iw hot smre nof lohc at fall tive.\n",
+      "\n",
+      "a yahasned wg forv oh tne tnard unibter oy tiuatms’s wohocribn fnaun a yomhd oh rnodes. at fis uohueiled ah i lirce stohe lahtel peirahc ih awice oy i rose, tne sgwpol oy tne uohsort oy tne smh cod nelaos. ahtracmahclg rnodes as ilso vhofh is tne aslihd oy tne vhacnts, hiwed iyter tne vhacnts oy siaht jonh oy jermsilew, ihd tne ulme it tne ehd oy unibter tnree boahted to ihotner nowe oy tne vhacnts it podrmw, so a trikelled tnere ihd fis hot too smrbrased to yahd unibter yomr uohueiled ah tne rewiahs oy tnear yort. a fis nofeker istohasned pg tne text! at toov we i fnale to uriuv at is a dadh't reuochase tne ehurgbtaoh is ihgtnahc ulissauil. fneh a yahillg prove at a dasuokered tnit tiuatms nid msed i uabner tnit fe tnomcnt nid peeh ahkehted ah saxteehtn uehtmrg yrihue. at seews tnit tne awberail uabner sunool fere wmun wore idkihued tnih fe nid ihg reisoh to exbeut. ay uomraer dmtg ash't exuatahc ehomcn yor gom bernibs tne unihue to dasuoker wore awberail uabners fall pe?\n",
+      "\n",
+      "tne ulme it tne ehd oy tnas unibter as kerg smccestake, ihd a nike pomcnt i tauvet to selumv to ahkestacite. a iw brettg smre a fis yollofed to tne tauvet oyyaue.\n",
+      "\n",
+      "ay gom uih uowe tneh fe heed gom to drob pg tne pratasn wmsemw peyore gom uowe omt. a tnahv tnere as sowetnahc tnere tnit fe heed ihd fall sehd i wessice to wg uohtiut ah roow tfehtg tfo tellahc tnew to exbeut gom ihd praeyahc tnew oh fnit to loov omt yor. at fomld pe cood ay gom uomld pe kerg dasureet ipomt tnit, pmt wive is wmun ymss is gom lave ipomt weetahc we ah selumv. a fall exbliah liter!\n",
+      "\n",
+      "ill tne pest,\n",
+      "\n",
+      "jodae\n",
+      "\n"
+     ]
+    }
+   ],
+   "source": [
+    "tt = ''.maketrans(trans)\n",
+    "print(ca.translate(tt))"
+   ]
+  },
+  {
+   "cell_type": "code",
+   "execution_count": 28,
    "metadata": {},
    "outputs": [
     {
   },
   {
    "cell_type": "code",
-   "execution_count": 61,
+   "execution_count": 29,
    "metadata": {},
    "outputs": [
     {
        " 'y': 'V'}"
       ]
      },
-     "execution_count": 61,
+     "execution_count": 29,
      "metadata": {},
      "output_type": "execute_result"
     }
   },
   {
    "cell_type": "code",
-   "execution_count": 62,
+   "execution_count": 30,
    "metadata": {},
    "outputs": [
     {
        " 'Z': 'c'}"
       ]
      },
-     "execution_count": 62,
+     "execution_count": 30,
      "metadata": {},
      "output_type": "execute_result"
     }
   },
   {
    "cell_type": "code",
-   "execution_count": 56,
+   "execution_count": 31,
+   "metadata": {},
+   "outputs": [
+    {
+     "data": {
+      "text/plain": [
+       "'bmoqfdaulxtkpivwgejshyrnc'"
+      ]
+     },
+     "execution_count": 31,
+     "metadata": {},
+     "output_type": "execute_result"
+    }
+   ],
+   "source": [
+    "cat(trans[k] for k in sorted(trans))"
+   ]
+  },
+  {
+   "cell_type": "code",
+   "execution_count": 32,
+   "metadata": {},
+   "outputs": [
+    {
+     "data": {
+      "text/plain": [
+       "'GAZFREQUNSLIBYCMDXTKHOPJV'"
+      ]
+     },
+     "execution_count": 32,
+     "metadata": {},
+     "output_type": "execute_result"
+    }
+   ],
+   "source": [
+    "cat({v: k for k, v in trans.items()}[tk] for tk in sorted(trans.values()))"
+   ]
+  },
+  {
+   "cell_type": "code",
+   "execution_count": 33,
    "metadata": {},
    "outputs": [
     {
        "2229"
       ]
      },
-     "execution_count": 56,
+     "execution_count": 33,
      "metadata": {},
      "output_type": "execute_result"
     }
   },
   {
    "cell_type": "code",
-   "execution_count": 57,
+   "execution_count": 34,
    "metadata": {},
    "outputs": [
     {
        "('arcanaimperii', -4159.598618934157)"
       ]
      },
-     "execution_count": 57,
+     "execution_count": 34,
      "metadata": {},
      "output_type": "execute_result"
     }
   },
   {
    "cell_type": "code",
-   "execution_count": 58,
+   "execution_count": 35,
    "metadata": {
     "scrolled": true
    },
        "'over the years the heroic role of agricola at watling street came to the notice of rome and two decades later he was appointed proconsul and governor of britannia by emperor vespasian a few years after his appointment vespasian ss on domitian became emperor and one of his first acts was to issue the order to implement the new imperial ciphers invented by the cipher school in the intervening years the ninth had been left to fight lonely skirmishes and battles from their base ate bora cum with fortitude and resolve they repeatedly drove the barbarians back into the cold heartlands of caledonia during one such skirmish varus was mortally wounded and agricola promoted the tribune marcus fidel i usca to to the legatus of the ninth one day the luck of the ninth seemed to change a reconnaissance squad reported that they had seen the aquila flying from a tree at mons grau pius in a camp ruled by a tribesman called cal gac us the new legatus recognised that the privations of along march had exhausted his men they were not ready for battle and ca to should have sent for reinforcements but the joy of seeing the lost aquila so close at hand clouded his judgement and he launched an attack under the cover of darkness fighting uphill against wave upon wave of barbarians the legions heroic efforts were frustrated by the sun rising to blind them as dawn broke the troops in the frontline gave way with exhaustion and the wild cal gac us dashed out of the sundown the blood soaked slope with his cavalry into the heart of the legion the legion rained flaming arrows upon the enemy and managed to un horse cal gac us taking him prisoner but could make no headway against the savage hordes and were unable to reach the stolen aquila worse was to come while ca to organised a retreat with the prisoner cal gac us in chains the remaining soldiers held the line against repeated charges by caledonian and iceni an tribesmen when the line finally broke ca to and many of the ninth legion had reached safety and took stock the cavalry were safe as were many of the brave legionnaires but to his horror ca to realised that in the battle he had lost the second aquila and worse the legions copy of the codex had also gone the documents left to me by agricola are unclear on this point did he know that the codex might have fallen into enemy hands and that a second aquila had been lost or did ca to assure him that the codex had been destroyed as part of an orderly retreat perhaps ca to was yet to rejoin agricola at the fort and communications from the battle had yet to reach him in a letter to emperor domitian agricola wrote most excellent emperor as you have most graciously requested i have finished my affairs herein britannia in preparation for returning to your side in rome it please sme to report to you that by acts of diplomacy and strength i have persuaded the northern rebels to yield to our army and to turnover to us the rebel cal gac us who has remained free since the wars against boudicca and the iceni his letter appears to have been a reply to new orders from rome in which domitian wrote my esteemed gnaeus upon receipt of your most recent letter i have been most troubled it appears clear to me that the situation in britannia has worsened and so i must ask you to return to meat rome with the utmost speed conduct your remaining affairs in the province and do not undertake any action which mayen flame the current tensions between yourself and the caledon ii the final line of the emperors letter set a deadline for agricola s return i shall expect you to have crossed the rubicon by the end of the year and perhaps he felt that contrition was a safer refuge whatever agricola knew at that point within a month his world had been turned upsidedown as further reports from caledonia made clear that his hope of restoration in the eyes of the emperor were in real jeopardy he set out to recover the two aquilae and to determine what had happened to the codex before returning to rome those who read on must search for the truth in the spiritual home of the amazons'"
       ]
      },
-     "execution_count": 58,
+     "execution_count": 35,
      "metadata": {},
      "output_type": "execute_result"
     }
   },
   {
    "cell_type": "code",
-   "execution_count": 59,
+   "execution_count": 36,
    "metadata": {},
    "outputs": [
     {
        "4084"
       ]
      },
-     "execution_count": 59,
+     "execution_count": 36,
      "metadata": {},
      "output_type": "execute_result"
     }
     "open('4b.plaintext', 'w').write(wcat(segment(vigenere_decipher(sanitise(cb), kb))))"
    ]
   },
+  {
+   "cell_type": "code",
+   "execution_count": 38,
+   "metadata": {},
+   "outputs": [],
+   "source": [
+    "pb = segment(vigenere_decipher(sanitise(cb), kb))"
+   ]
+  },
+  {
+   "cell_type": "code",
+   "execution_count": 42,
+   "metadata": {},
+   "outputs": [
+    {
+     "data": {
+      "text/plain": [
+       "['over the years the heroic role of agricola at watling street came to the notice of rome and two',\n",
+       " 'decades later he was appointed proconsul and governor of britannia by emperor vespasian a few years',\n",
+       " 'after his appointment vespasian ss on domitian became emperor and one of his first acts was to issue',\n",
+       " 'the order to implement the new imperial ciphers invented by the cipher school in the intervening',\n",
+       " 'years the ninth had been left to fight lonely skirmishes and battles from their base ate bora cum',\n",
+       " 'with fortitude and resolve they repeatedly drove the barbarians back into the cold heartlands of',\n",
+       " 'caledonia during one such skirmish varus was mortally wounded and agricola promoted the tribune',\n",
+       " 'marcus fidel i usca to to the legatus of the ninth one day the luck of the ninth seemed to change a',\n",
+       " 'reconnaissance squad reported that they had seen the aquila flying from a tree at mons grau pius in',\n",
+       " 'a camp ruled by a tribesman called cal gac us the new legatus recognised that the privations of',\n",
+       " 'along march had exhausted his men they were not ready for battle and ca to should have sent for',\n",
+       " 'reinforcements but the joy of seeing the lost aquila so close at hand clouded his judgement and he',\n",
+       " 'launched an attack under the cover of darkness fighting uphill against wave upon wave of barbarians',\n",
+       " 'the legions heroic efforts were frustrated by the sun rising to blind them as dawn broke the troops',\n",
+       " 'in the frontline gave way with exhaustion and the wild cal gac us dashed out of the sundown the',\n",
+       " 'blood soaked slope with his cavalry into the heart of the legion the legion rained flaming arrows',\n",
+       " 'upon the enemy and managed to un horse cal gac us taking him prisoner but could make no headway',\n",
+       " 'against the savage hordes and were unable to reach the stolen aquila worse was to come while ca to',\n",
+       " 'organised a retreat with the prisoner cal gac us in chains the remaining soldiers held the line',\n",
+       " 'against repeated charges by caledonian and iceni an tribesmen when the line finally broke ca to and',\n",
+       " 'many of the ninth legion had reached safety and took stock the cavalry were safe as were many of the',\n",
+       " 'brave legionnaires but to his horror ca to realised that in the battle he had lost the second aquila',\n",
+       " 'and worse the legions copy of the codex had also gone the documents left to me by agricola are',\n",
+       " 'unclear on this point did he know that the codex might have fallen into enemy hands and that a',\n",
+       " 'second aquila had been lost or did ca to assure him that the codex had been destroyed as part of an',\n",
+       " 'orderly retreat perhaps ca to was yet to rejoin agricola at the fort and communications from the',\n",
+       " 'battle had yet to reach him in a letter to emperor domitian agricola wrote most excellent emperor as',\n",
+       " 'you have most graciously requested i have finished my affairs herein britannia in preparation for',\n",
+       " 'returning to your side in rome it please sme to report to you that by acts of diplomacy and strength',\n",
+       " 'i have persuaded the northern rebels to yield to our army and to turnover to us the rebel cal gac us',\n",
+       " 'who has remained free since the wars against boudicca and the iceni his letter appears to have been',\n",
+       " 'a reply to new orders from rome in which domitian wrote my esteemed gnaeus upon receipt of your most',\n",
+       " 'recent letter i have been most troubled it appears clear to me that the situation in britannia has',\n",
+       " 'worsened and so i must ask you to return to meat rome with the utmost speed conduct your remaining',\n",
+       " 'affairs in the province and do not undertake any action which mayen flame the current tensions',\n",
+       " 'between yourself and the caledon ii the final line of the emperors letter set a deadline for',\n",
+       " 'agricola s return i shall expect you to have crossed the rubicon by the end of the year and perhaps',\n",
+       " 'he felt that contrition was a safer refuge whatever agricola knew at that point within a month his',\n",
+       " 'world had been turned upsidedown as further reports from caledonia made clear that his hope of',\n",
+       " 'restoration in the eyes of the emperor were in real jeopardy he set out to recover the two aquilae',\n",
+       " 'and to determine what had happened to the codex before returning to rome those who read on must',\n",
+       " 'search for the truth in the spiritual home of the amazons']"
+      ]
+     },
+     "execution_count": 42,
+     "metadata": {},
+     "output_type": "execute_result"
+    }
+   ],
+   "source": [
+    "tpack(pb)"
+   ]
+  },
   {
    "cell_type": "code",
    "execution_count": null,
    "name": "python",
    "nbconvert_exporter": "python",
    "pygments_lexer": "ipython3",
-   "version": "3.5.2"
+   "version": "3.5.3"
   }
  },
  "nbformat": 4,