Started on documentation
[szyfrow.git] / docs / szyfrow / railfence.html
diff --git a/docs/szyfrow/railfence.html b/docs/szyfrow/railfence.html
new file mode 100644 (file)
index 0000000..ab6dc3b
--- /dev/null
@@ -0,0 +1,550 @@
+<!doctype html>
+<html lang="en">
+<head>
+<meta charset="utf-8">
+<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1" />
+<meta name="generator" content="pdoc 0.9.2" />
+<title>szyfrow.railfence API documentation</title>
+<meta name="description" content="[Railfence transposition cipher](https://en.wikipedia.org/wiki/Rail_fence_cipher) …" />
+<link rel="preload stylesheet" as="style" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/11.0.1/sanitize.min.css" integrity="sha256-PK9q560IAAa6WVRRh76LtCaI8pjTJ2z11v0miyNNjrs=" crossorigin>
+<link rel="preload stylesheet" as="style" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/11.0.1/typography.min.css" integrity="sha256-7l/o7C8jubJiy74VsKTidCy1yBkRtiUGbVkYBylBqUg=" crossorigin>
+<link rel="stylesheet preload" as="style" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.1.1/styles/github.min.css" crossorigin>
+<style>:root{--highlight-color:#fe9}.flex{display:flex !important}body{line-height:1.5em}#content{padding:20px}#sidebar{padding:30px;overflow:hidden}#sidebar > *:last-child{margin-bottom:2cm}.http-server-breadcrumbs{font-size:130%;margin:0 0 15px 0}#footer{font-size:.75em;padding:5px 30px;border-top:1px solid #ddd;text-align:right}#footer p{margin:0 0 0 1em;display:inline-block}#footer p:last-child{margin-right:30px}h1,h2,h3,h4,h5{font-weight:300}h1{font-size:2.5em;line-height:1.1em}h2{font-size:1.75em;margin:1em 0 .50em 0}h3{font-size:1.4em;margin:25px 0 10px 0}h4{margin:0;font-size:105%}h1:target,h2:target,h3:target,h4:target,h5:target,h6:target{background:var(--highlight-color);padding:.2em 0}a{color:#058;text-decoration:none;transition:color .3s ease-in-out}a:hover{color:#e82}.title code{font-weight:bold}h2[id^="header-"]{margin-top:2em}.ident{color:#900}pre code{background:#f8f8f8;font-size:.8em;line-height:1.4em}code{background:#f2f2f1;padding:1px 4px;overflow-wrap:break-word}h1 code{background:transparent}pre{background:#f8f8f8;border:0;border-top:1px solid #ccc;border-bottom:1px solid #ccc;margin:1em 0;padding:1ex}#http-server-module-list{display:flex;flex-flow:column}#http-server-module-list div{display:flex}#http-server-module-list dt{min-width:10%}#http-server-module-list p{margin-top:0}.toc ul,#index{list-style-type:none;margin:0;padding:0}#index code{background:transparent}#index h3{border-bottom:1px solid #ddd}#index ul{padding:0}#index h4{margin-top:.6em;font-weight:bold}@media (min-width:200ex){#index .two-column{column-count:2}}@media (min-width:300ex){#index .two-column{column-count:3}}dl{margin-bottom:2em}dl dl:last-child{margin-bottom:4em}dd{margin:0 0 1em 3em}#header-classes + dl > dd{margin-bottom:3em}dd dd{margin-left:2em}dd p{margin:10px 0}.name{background:#eee;font-weight:bold;font-size:.85em;padding:5px 10px;display:inline-block;min-width:40%}.name:hover{background:#e0e0e0}dt:target .name{background:var(--highlight-color)}.name > span:first-child{white-space:nowrap}.name.class > span:nth-child(2){margin-left:.4em}.inherited{color:#999;border-left:5px solid #eee;padding-left:1em}.inheritance em{font-style:normal;font-weight:bold}.desc h2{font-weight:400;font-size:1.25em}.desc h3{font-size:1em}.desc dt code{background:inherit}.source summary,.git-link-div{color:#666;text-align:right;font-weight:400;font-size:.8em;text-transform:uppercase}.source summary > *{white-space:nowrap;cursor:pointer}.git-link{color:inherit;margin-left:1em}.source pre{max-height:500px;overflow:auto;margin:0}.source pre code{font-size:12px;overflow:visible}.hlist{list-style:none}.hlist li{display:inline}.hlist li:after{content:',\2002'}.hlist li:last-child:after{content:none}.hlist .hlist{display:inline;padding-left:1em}img{max-width:100%}td{padding:0 .5em}.admonition{padding:.1em .5em;margin-bottom:1em}.admonition-title{font-weight:bold}.admonition.note,.admonition.info,.admonition.important{background:#aef}.admonition.todo,.admonition.versionadded,.admonition.tip,.admonition.hint{background:#dfd}.admonition.warning,.admonition.versionchanged,.admonition.deprecated{background:#fd4}.admonition.error,.admonition.danger,.admonition.caution{background:lightpink}</style>
+<style media="screen and (min-width: 700px)">@media screen and (min-width:700px){#sidebar{width:30%;height:100vh;overflow:auto;position:sticky;top:0}#content{width:70%;max-width:100ch;padding:3em 4em;border-left:1px solid #ddd}pre code{font-size:1em}.item .name{font-size:1em}main{display:flex;flex-direction:row-reverse;justify-content:flex-end}.toc ul ul,#index ul{padding-left:1.5em}.toc > ul > li{margin-top:.5em}}</style>
+<style media="print">@media print{#sidebar h1{page-break-before:always}.source{display:none}}@media print{*{background:transparent !important;color:#000 !important;box-shadow:none !important;text-shadow:none !important}a[href]:after{content:" (" attr(href) ")";font-size:90%}a[href][title]:after{content:none}abbr[title]:after{content:" (" attr(title) ")"}.ir a:after,a[href^="javascript:"]:after,a[href^="#"]:after{content:""}pre,blockquote{border:1px solid #999;page-break-inside:avoid}thead{display:table-header-group}tr,img{page-break-inside:avoid}img{max-width:100% !important}@page{margin:0.5cm}p,h2,h3{orphans:3;widows:3}h1,h2,h3,h4,h5,h6{page-break-after:avoid}}</style>
+<script defer src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.1.1/highlight.min.js" integrity="sha256-Uv3H6lx7dJmRfRvH8TH6kJD1TSK1aFcwgx+mdg3epi8=" crossorigin></script>
+<script>window.addEventListener('DOMContentLoaded', () => hljs.initHighlighting())</script>
+</head>
+<body>
+<main>
+<article id="content">
+<header>
+<h1 class="title">Module <code>szyfrow.railfence</code></h1>
+</header>
+<section id="section-intro">
+<p><a href="https://en.wikipedia.org/wiki/Rail_fence_cipher">Railfence transposition cipher</a>.</p>
+<p>Works by splitting the text into sections, then reading across them to
+generate the rows in the cipher. The rows are then combined to form the
+ciphertext.</p>
+<p>Example: the plaintext "hellotherefriends", with a height of four, written
+out in the railfence as
+h h i
+etere*
+lorfns
+l e d
+(with the * showing the one character to finish the last section).
+Each 'section' is two columns, but unfolded. In the example, the first
+section is 'hellot'.</p>
+<details class="source">
+<summary>
+<span>Expand source code</span>
+</summary>
+<pre><code class="python">&#34;&#34;&#34;[Railfence transposition cipher](https://en.wikipedia.org/wiki/Rail_fence_cipher).
+
+Works by splitting the text into sections, then reading across them to
+generate the rows in the cipher. The rows are then combined to form the
+ciphertext.
+
+Example: the plaintext &#34;hellotherefriends&#34;, with a height of four, written 
+out in the railfence as 
+   h h i
+   etere*
+   lorfns
+   l e d
+(with the * showing the one character to finish the last section). 
+Each &#39;section&#39; is two columns, but unfolded. In the example, the first
+section is &#39;hellot&#39;.
+&#34;&#34;&#34;
+import math
+from enum import Enum
+from itertools import starmap, zip_longest
+from szyfrow.support.utilities import *
+from szyfrow.support.language_models import *
+
+
+def railfence_encipher(message, height, fillvalue=&#39;&#39;):
+    &#34;&#34;&#34;Railfence cipher.
+    Works by splitting the text into sections, then reading across them to
+    generate the rows in the cipher. The rows are then combined to form the
+    ciphertext.
+
+    Example: the plaintext &#34;hellotherefriends&#34;, with a height of four, written 
+    out in the railfence as 
+       h h i
+       etere*
+       lorfns
+       l e d
+    (with the * showing the one character to finish the last section). 
+    Each &#39;section&#39; is two columns, but unfolded. In the example, the first
+    section is &#39;hellot&#39;.
+
+    &gt;&gt;&gt; railfence_encipher(&#39;hellothereavastmeheartiesthisisalongpieceoftextfortestingrailfenceciphers&#39;, 2, fillvalue=&#39;!&#39;)
+    &#39;hlohraateerishsslnpeefetotsigaleccpeselteevsmhatetiiaogicotxfretnrifneihr!&#39;
+    &gt;&gt;&gt; railfence_encipher(&#39;hellothereavastmeheartiesthisisalongpieceoftextfortestingrailfenceciphers&#39;, 3, fillvalue=&#39;!&#39;)
+    &#39;horaersslpeeosglcpselteevsmhatetiiaogicotxfretnrifneihr!!lhateihsnefttiaece!&#39;
+    &gt;&gt;&gt; railfence_encipher(&#39;hellothereavastmeheartiesthisisalongpieceoftextfortestingrailfenceciphers&#39;, 5, fillvalue=&#39;!&#39;)
+    &#39;hresleogcseeemhetaocofrnrner!!lhateihsnefttiaece!!ltvsatiigitxetifih!!oarspeslp!&#39;
+    &gt;&gt;&gt; railfence_encipher(&#39;hellothereavastmeheartiesthisisalongpieceoftextfortestingrailfenceciphers&#39;, 10, fillvalue=&#39;!&#39;)
+    &#39;hepisehagitnr!!lernesge!!lmtocerh!!otiletap!!tseaorii!!hassfolc!!evtitffe!!rahsetec!!eixn!&#39;
+    &gt;&gt;&gt; railfence_encipher(&#39;hellothereavastmeheartiesthisisalongpieceoftextfortestingrailfenceciphers&#39;, 3)
+    &#39;horaersslpeeosglcpselteevsmhatetiiaogicotxfretnrifneihrlhateihsnefttiaece&#39;
+    &gt;&gt;&gt; railfence_encipher(&#39;hellothereavastmeheartiesthisisalongpieceoftextfortestingrailfenceciphers&#39;, 5)
+    &#39;hresleogcseeemhetaocofrnrnerlhateihsnefttiaeceltvsatiigitxetifihoarspeslp&#39;
+    &gt;&gt;&gt; railfence_encipher(&#39;hellothereavastmeheartiesthisisalongpieceoftextfortestingrailfenceciphers&#39;, 7)
+    &#39;haspolsevsetgifrifrlatihnettaeelemtiocxernhorersleesgcptehaiaottneihesfic&#39;
+    &#34;&#34;&#34;
+    sections = chunks(message, (height - 1) * 2, fillvalue=fillvalue)
+    n_sections = len(sections)
+    # Add the top row
+    rows = [cat([s[0] for s in sections])]
+    # process the middle rows of the grid
+    for r in range(1, height-1):
+        rows += [cat([s[r:r+1] + s[height*2-r-2:height*2-r-1] for s in sections])]
+    # process the bottom row
+    rows += [cat([s[height - 1:height] for s in sections])]
+    # rows += [wcat([s[height - 1] for s in sections])]
+    return cat(rows)
+
+def railfence_decipher(message, height, fillvalue=&#39;&#39;):
+    &#34;&#34;&#34;Railfence decipher. 
+    Works by reconstructing the grid used to generate the ciphertext, then
+    unfolding the sections so the text can be concatenated together.
+
+    Example: given the ciphertext &#39;hhieterelorfnsled&#39; and a height of 4, first
+    work out that the second row has a character missing, find the rows of the
+    grid, then split the section into its two columns.
+
+    &#39;hhieterelorfnsled&#39; is split into
+        h h i
+        etere
+        lorfns
+        l e d
+    (spaces added for clarity), which is stored in &#39;rows&#39;. This is then split
+    into &#39;down_rows&#39; and &#39;up_rows&#39;:
+
+    down_rows:
+       hhi
+       eee
+       lrn
+       led
+
+    up_rows:
+       tr
+       ofs
+
+    These are then zipped together (after the up_rows are reversed) to recover 
+    the plaintext.
+
+    Most of the procedure is about finding the correct lengths for each row then
+    splitting the ciphertext into those rows.
+
+    &gt;&gt;&gt; railfence_decipher(&#39;hlohraateerishsslnpeefetotsigaleccpeselteevsmhatetiiaogicotxfretnrifneihr!&#39;, 2).strip(&#39;!&#39;)
+    &#39;hellothereavastmeheartiesthisisalongpieceoftextfortestingrailfenceciphers&#39;
+    &gt;&gt;&gt; railfence_decipher(&#39;horaersslpeeosglcpselteevsmhatetiiaogicotxfretnrifneihr!!lhateihsnefttiaece!&#39;, 3).strip(&#39;!&#39;)
+    &#39;hellothereavastmeheartiesthisisalongpieceoftextfortestingrailfenceciphers&#39;
+    &gt;&gt;&gt; railfence_decipher(&#39;hresleogcseeemhetaocofrnrner!!lhateihsnefttiaece!!ltvsatiigitxetifih!!oarspeslp!&#39;, 5).strip(&#39;!&#39;)
+    &#39;hellothereavastmeheartiesthisisalongpieceoftextfortestingrailfenceciphers&#39;
+    &gt;&gt;&gt; railfence_decipher(&#39;hepisehagitnr!!lernesge!!lmtocerh!!otiletap!!tseaorii!!hassfolc!!evtitffe!!rahsetec!!eixn!&#39;, 10).strip(&#39;!&#39;)
+    &#39;hellothereavastmeheartiesthisisalongpieceoftextfortestingrailfenceciphers&#39;
+    &gt;&gt;&gt; railfence_decipher(&#39;horaersslpeeosglcpselteevsmhatetiiaogicotxfretnrifneihrlhateihsnefttiaece&#39;, 3)
+    &#39;hellothereavastmeheartiesthisisalongpieceoftextfortestingrailfenceciphers&#39;
+    &gt;&gt;&gt; railfence_decipher(&#39;hresleogcseeemhetaocofrnrnerlhateihsnefttiaeceltvsatiigitxetifihoarspeslp&#39;, 5)
+    &#39;hellothereavastmeheartiesthisisalongpieceoftextfortestingrailfenceciphers&#39;
+    &gt;&gt;&gt; railfence_decipher(&#39;haspolsevsetgifrifrlatihnettaeelemtiocxernhorersleesgcptehaiaottneihesfic&#39;, 7)
+    &#39;hellothereavastmeheartiesthisisalongpieceoftextfortestingrailfenceciphers&#39;
+    &#34;&#34;&#34;
+    # find the number and size of the sections, including how many characters
+    #   are missing for a full grid
+    n_sections = math.ceil(len(message) / ((height - 1) * 2))
+    padding_to_add = n_sections * (height - 1) * 2 - len(message)
+    # row_lengths are for the both up rows and down rows
+    row_lengths = [n_sections] * (height - 1) * 2
+    for i in range((height - 1) * 2 - 1, (height - 1) * 2 - (padding_to_add + 1), -1):
+        row_lengths[i] -= 1
+    # folded_rows are the combined row lengths in the middle of the railfence
+    folded_row_lengths = [row_lengths[0]]
+    for i in range(1, height-1):
+        folded_row_lengths += [row_lengths[i] + row_lengths[-i]]
+    folded_row_lengths += [row_lengths[height - 1]]
+    # find the rows that form the railfence grid
+    rows = []
+    row_start = 0
+    for i in folded_row_lengths:
+        rows += [message[row_start:row_start + i]]
+        row_start += i
+    # split the rows into the &#39;down_rows&#39; (those that form the first column of
+    #   a section) and the &#39;up_rows&#39; (those that ofrm the second column of a 
+    #   section).
+    down_rows = [rows[0]]
+    up_rows = []
+    for i in range(1, height-1):
+        down_rows += [cat([c for n, c in enumerate(rows[i]) if n % 2 == 0])]
+        up_rows += [cat([c for n, c in enumerate(rows[i]) if n % 2 == 1])]
+    down_rows += [rows[-1]]
+    up_rows.reverse()
+    return cat(c for r in zip_longest(*(down_rows + up_rows), fillvalue=&#39;&#39;) for c in r)
+
+
+def railfence_break(message, max_key_length=20,
+                     fitness=Pbigrams, chunksize=500):
+    &#34;&#34;&#34;Breaks a railfence cipher using a range of lengths and
+    n-gram frequency analysis
+
+    &gt;&gt;&gt; railfence_break(railfence_encipher(sanitise( \
+            &#34;It is a truth universally acknowledged, that a single man in \
+             possession of a good fortune, must be in want of a wife. However \
+             little known the feelings or views of such a man may be on his \
+             first entering a neighbourhood, this truth is so well fixed in \
+             the minds of the surrounding families, that he is considered the \
+             rightful property of some one or other of their daughters.&#34;), \
+        7)) # doctest: +ELLIPSIS
+    (7, -709.46467226...)
+    &gt;&gt;&gt; railfence_break(railfence_encipher(sanitise( \
+            &#34;It is a truth universally acknowledged, that a single man in \
+             possession of a good fortune, must be in want of a wife. However \
+             little known the feelings or views of such a man may be on his \
+             first entering a neighbourhood, this truth is so well fixed in \
+             the minds of the surrounding families, that he is considered the \
+             rightful property of some one or other of their daughters.&#34;), \
+        7), \
+        fitness=Ptrigrams) # doctest: +ELLIPSIS
+    (7, -997.0129085...)
+    &#34;&#34;&#34;
+    def worker(message, height, fitness):
+        plaintext = railfence_decipher(message, height)
+        fit = fitness(plaintext)
+        return height, fit
+
+    sanitised_message = sanitise(message)
+    results = starmap(worker, [(sanitised_message, i, fitness)
+                               for i in range(2, max_key_length+1)])
+    return max(results, key=lambda k: k[1])</code></pre>
+</details>
+</section>
+<section>
+</section>
+<section>
+</section>
+<section>
+<h2 class="section-title" id="header-functions">Functions</h2>
+<dl>
+<dt id="szyfrow.railfence.cat"><code class="name flex">
+<span>def <span class="ident">cat</span></span>(<span>iterable, /)</span>
+</code></dt>
+<dd>
+<div class="desc"><p>Concatenate any number of strings.</p>
+<p>The string whose method is called is inserted in between each given string.
+The result is returned as a new string.</p>
+<p>Example: '.'.join(['ab', 'pq', 'rs']) -&gt; 'ab.pq.rs'</p></div>
+</dd>
+<dt id="szyfrow.railfence.lcat"><code class="name flex">
+<span>def <span class="ident">lcat</span></span>(<span>iterable, /)</span>
+</code></dt>
+<dd>
+<div class="desc"><p>Concatenate any number of strings.</p>
+<p>The string whose method is called is inserted in between each given string.
+The result is returned as a new string.</p>
+<p>Example: '.'.join(['ab', 'pq', 'rs']) -&gt; 'ab.pq.rs'</p></div>
+</dd>
+<dt id="szyfrow.railfence.railfence_break"><code class="name flex">
+<span>def <span class="ident">railfence_break</span></span>(<span>message, max_key_length=20, fitness=&lt;function Pbigrams&gt;, chunksize=500)</span>
+</code></dt>
+<dd>
+<div class="desc"><p>Breaks a railfence cipher using a range of lengths and
+n-gram frequency analysis</p>
+<pre><code class="language-python-repl">&gt;&gt;&gt; railfence_break(railfence_encipher(sanitise(             &quot;It is a truth universally acknowledged, that a single man in              possession of a good fortune, must be in want of a wife. However              little known the feelings or views of such a man may be on his              first entering a neighbourhood, this truth is so well fixed in              the minds of the surrounding families, that he is considered the              rightful property of some one or other of their daughters.&quot;),         7)) # doctest: +ELLIPSIS
+(7, -709.46467226...)
+&gt;&gt;&gt; railfence_break(railfence_encipher(sanitise(             &quot;It is a truth universally acknowledged, that a single man in              possession of a good fortune, must be in want of a wife. However              little known the feelings or views of such a man may be on his              first entering a neighbourhood, this truth is so well fixed in              the minds of the surrounding families, that he is considered the              rightful property of some one or other of their daughters.&quot;),         7),         fitness=Ptrigrams) # doctest: +ELLIPSIS
+(7, -997.0129085...)
+</code></pre></div>
+<details class="source">
+<summary>
+<span>Expand source code</span>
+</summary>
+<pre><code class="python">def railfence_break(message, max_key_length=20,
+                     fitness=Pbigrams, chunksize=500):
+    &#34;&#34;&#34;Breaks a railfence cipher using a range of lengths and
+    n-gram frequency analysis
+
+    &gt;&gt;&gt; railfence_break(railfence_encipher(sanitise( \
+            &#34;It is a truth universally acknowledged, that a single man in \
+             possession of a good fortune, must be in want of a wife. However \
+             little known the feelings or views of such a man may be on his \
+             first entering a neighbourhood, this truth is so well fixed in \
+             the minds of the surrounding families, that he is considered the \
+             rightful property of some one or other of their daughters.&#34;), \
+        7)) # doctest: +ELLIPSIS
+    (7, -709.46467226...)
+    &gt;&gt;&gt; railfence_break(railfence_encipher(sanitise( \
+            &#34;It is a truth universally acknowledged, that a single man in \
+             possession of a good fortune, must be in want of a wife. However \
+             little known the feelings or views of such a man may be on his \
+             first entering a neighbourhood, this truth is so well fixed in \
+             the minds of the surrounding families, that he is considered the \
+             rightful property of some one or other of their daughters.&#34;), \
+        7), \
+        fitness=Ptrigrams) # doctest: +ELLIPSIS
+    (7, -997.0129085...)
+    &#34;&#34;&#34;
+    def worker(message, height, fitness):
+        plaintext = railfence_decipher(message, height)
+        fit = fitness(plaintext)
+        return height, fit
+
+    sanitised_message = sanitise(message)
+    results = starmap(worker, [(sanitised_message, i, fitness)
+                               for i in range(2, max_key_length+1)])
+    return max(results, key=lambda k: k[1])</code></pre>
+</details>
+</dd>
+<dt id="szyfrow.railfence.railfence_decipher"><code class="name flex">
+<span>def <span class="ident">railfence_decipher</span></span>(<span>message, height, fillvalue='')</span>
+</code></dt>
+<dd>
+<div class="desc"><p>Railfence decipher.
+Works by reconstructing the grid used to generate the ciphertext, then
+unfolding the sections so the text can be concatenated together.</p>
+<p>Example: given the ciphertext 'hhieterelorfnsled' and a height of 4, first
+work out that the second row has a character missing, find the rows of the
+grid, then split the section into its two columns.</p>
+<p>'hhieterelorfnsled' is split into
+h h i
+etere
+lorfns
+l e d
+(spaces added for clarity), which is stored in 'rows'. This is then split
+into 'down_rows' and 'up_rows':</p>
+<p>down_rows:
+hhi
+eee
+lrn
+led</p>
+<p>up_rows:
+tr
+ofs</p>
+<p>These are then zipped together (after the up_rows are reversed) to recover
+the plaintext.</p>
+<p>Most of the procedure is about finding the correct lengths for each row then
+splitting the ciphertext into those rows.</p>
+<pre><code class="language-python-repl">&gt;&gt;&gt; railfence_decipher('hlohraateerishsslnpeefetotsigaleccpeselteevsmhatetiiaogicotxfretnrifneihr!', 2).strip('!')
+'hellothereavastmeheartiesthisisalongpieceoftextfortestingrailfenceciphers'
+&gt;&gt;&gt; railfence_decipher('horaersslpeeosglcpselteevsmhatetiiaogicotxfretnrifneihr!!lhateihsnefttiaece!', 3).strip('!')
+'hellothereavastmeheartiesthisisalongpieceoftextfortestingrailfenceciphers'
+&gt;&gt;&gt; railfence_decipher('hresleogcseeemhetaocofrnrner!!lhateihsnefttiaece!!ltvsatiigitxetifih!!oarspeslp!', 5).strip('!')
+'hellothereavastmeheartiesthisisalongpieceoftextfortestingrailfenceciphers'
+&gt;&gt;&gt; railfence_decipher('hepisehagitnr!!lernesge!!lmtocerh!!otiletap!!tseaorii!!hassfolc!!evtitffe!!rahsetec!!eixn!', 10).strip('!')
+'hellothereavastmeheartiesthisisalongpieceoftextfortestingrailfenceciphers'
+&gt;&gt;&gt; railfence_decipher('horaersslpeeosglcpselteevsmhatetiiaogicotxfretnrifneihrlhateihsnefttiaece', 3)
+'hellothereavastmeheartiesthisisalongpieceoftextfortestingrailfenceciphers'
+&gt;&gt;&gt; railfence_decipher('hresleogcseeemhetaocofrnrnerlhateihsnefttiaeceltvsatiigitxetifihoarspeslp', 5)
+'hellothereavastmeheartiesthisisalongpieceoftextfortestingrailfenceciphers'
+&gt;&gt;&gt; railfence_decipher('haspolsevsetgifrifrlatihnettaeelemtiocxernhorersleesgcptehaiaottneihesfic', 7)
+'hellothereavastmeheartiesthisisalongpieceoftextfortestingrailfenceciphers'
+</code></pre></div>
+<details class="source">
+<summary>
+<span>Expand source code</span>
+</summary>
+<pre><code class="python">def railfence_decipher(message, height, fillvalue=&#39;&#39;):
+    &#34;&#34;&#34;Railfence decipher. 
+    Works by reconstructing the grid used to generate the ciphertext, then
+    unfolding the sections so the text can be concatenated together.
+
+    Example: given the ciphertext &#39;hhieterelorfnsled&#39; and a height of 4, first
+    work out that the second row has a character missing, find the rows of the
+    grid, then split the section into its two columns.
+
+    &#39;hhieterelorfnsled&#39; is split into
+        h h i
+        etere
+        lorfns
+        l e d
+    (spaces added for clarity), which is stored in &#39;rows&#39;. This is then split
+    into &#39;down_rows&#39; and &#39;up_rows&#39;:
+
+    down_rows:
+       hhi
+       eee
+       lrn
+       led
+
+    up_rows:
+       tr
+       ofs
+
+    These are then zipped together (after the up_rows are reversed) to recover 
+    the plaintext.
+
+    Most of the procedure is about finding the correct lengths for each row then
+    splitting the ciphertext into those rows.
+
+    &gt;&gt;&gt; railfence_decipher(&#39;hlohraateerishsslnpeefetotsigaleccpeselteevsmhatetiiaogicotxfretnrifneihr!&#39;, 2).strip(&#39;!&#39;)
+    &#39;hellothereavastmeheartiesthisisalongpieceoftextfortestingrailfenceciphers&#39;
+    &gt;&gt;&gt; railfence_decipher(&#39;horaersslpeeosglcpselteevsmhatetiiaogicotxfretnrifneihr!!lhateihsnefttiaece!&#39;, 3).strip(&#39;!&#39;)
+    &#39;hellothereavastmeheartiesthisisalongpieceoftextfortestingrailfenceciphers&#39;
+    &gt;&gt;&gt; railfence_decipher(&#39;hresleogcseeemhetaocofrnrner!!lhateihsnefttiaece!!ltvsatiigitxetifih!!oarspeslp!&#39;, 5).strip(&#39;!&#39;)
+    &#39;hellothereavastmeheartiesthisisalongpieceoftextfortestingrailfenceciphers&#39;
+    &gt;&gt;&gt; railfence_decipher(&#39;hepisehagitnr!!lernesge!!lmtocerh!!otiletap!!tseaorii!!hassfolc!!evtitffe!!rahsetec!!eixn!&#39;, 10).strip(&#39;!&#39;)
+    &#39;hellothereavastmeheartiesthisisalongpieceoftextfortestingrailfenceciphers&#39;
+    &gt;&gt;&gt; railfence_decipher(&#39;horaersslpeeosglcpselteevsmhatetiiaogicotxfretnrifneihrlhateihsnefttiaece&#39;, 3)
+    &#39;hellothereavastmeheartiesthisisalongpieceoftextfortestingrailfenceciphers&#39;
+    &gt;&gt;&gt; railfence_decipher(&#39;hresleogcseeemhetaocofrnrnerlhateihsnefttiaeceltvsatiigitxetifihoarspeslp&#39;, 5)
+    &#39;hellothereavastmeheartiesthisisalongpieceoftextfortestingrailfenceciphers&#39;
+    &gt;&gt;&gt; railfence_decipher(&#39;haspolsevsetgifrifrlatihnettaeelemtiocxernhorersleesgcptehaiaottneihesfic&#39;, 7)
+    &#39;hellothereavastmeheartiesthisisalongpieceoftextfortestingrailfenceciphers&#39;
+    &#34;&#34;&#34;
+    # find the number and size of the sections, including how many characters
+    #   are missing for a full grid
+    n_sections = math.ceil(len(message) / ((height - 1) * 2))
+    padding_to_add = n_sections * (height - 1) * 2 - len(message)
+    # row_lengths are for the both up rows and down rows
+    row_lengths = [n_sections] * (height - 1) * 2
+    for i in range((height - 1) * 2 - 1, (height - 1) * 2 - (padding_to_add + 1), -1):
+        row_lengths[i] -= 1
+    # folded_rows are the combined row lengths in the middle of the railfence
+    folded_row_lengths = [row_lengths[0]]
+    for i in range(1, height-1):
+        folded_row_lengths += [row_lengths[i] + row_lengths[-i]]
+    folded_row_lengths += [row_lengths[height - 1]]
+    # find the rows that form the railfence grid
+    rows = []
+    row_start = 0
+    for i in folded_row_lengths:
+        rows += [message[row_start:row_start + i]]
+        row_start += i
+    # split the rows into the &#39;down_rows&#39; (those that form the first column of
+    #   a section) and the &#39;up_rows&#39; (those that ofrm the second column of a 
+    #   section).
+    down_rows = [rows[0]]
+    up_rows = []
+    for i in range(1, height-1):
+        down_rows += [cat([c for n, c in enumerate(rows[i]) if n % 2 == 0])]
+        up_rows += [cat([c for n, c in enumerate(rows[i]) if n % 2 == 1])]
+    down_rows += [rows[-1]]
+    up_rows.reverse()
+    return cat(c for r in zip_longest(*(down_rows + up_rows), fillvalue=&#39;&#39;) for c in r)</code></pre>
+</details>
+</dd>
+<dt id="szyfrow.railfence.railfence_encipher"><code class="name flex">
+<span>def <span class="ident">railfence_encipher</span></span>(<span>message, height, fillvalue='')</span>
+</code></dt>
+<dd>
+<div class="desc"><p>Railfence cipher.
+Works by splitting the text into sections, then reading across them to
+generate the rows in the cipher. The rows are then combined to form the
+ciphertext.</p>
+<p>Example: the plaintext "hellotherefriends", with a height of four, written
+out in the railfence as
+h h i
+etere*
+lorfns
+l e d
+(with the * showing the one character to finish the last section).
+Each 'section' is two columns, but unfolded. In the example, the first
+section is 'hellot'.</p>
+<pre><code class="language-python-repl">&gt;&gt;&gt; railfence_encipher('hellothereavastmeheartiesthisisalongpieceoftextfortestingrailfenceciphers', 2, fillvalue='!')
+'hlohraateerishsslnpeefetotsigaleccpeselteevsmhatetiiaogicotxfretnrifneihr!'
+&gt;&gt;&gt; railfence_encipher('hellothereavastmeheartiesthisisalongpieceoftextfortestingrailfenceciphers', 3, fillvalue='!')
+'horaersslpeeosglcpselteevsmhatetiiaogicotxfretnrifneihr!!lhateihsnefttiaece!'
+&gt;&gt;&gt; railfence_encipher('hellothereavastmeheartiesthisisalongpieceoftextfortestingrailfenceciphers', 5, fillvalue='!')
+'hresleogcseeemhetaocofrnrner!!lhateihsnefttiaece!!ltvsatiigitxetifih!!oarspeslp!'
+&gt;&gt;&gt; railfence_encipher('hellothereavastmeheartiesthisisalongpieceoftextfortestingrailfenceciphers', 10, fillvalue='!')
+'hepisehagitnr!!lernesge!!lmtocerh!!otiletap!!tseaorii!!hassfolc!!evtitffe!!rahsetec!!eixn!'
+&gt;&gt;&gt; railfence_encipher('hellothereavastmeheartiesthisisalongpieceoftextfortestingrailfenceciphers', 3)
+'horaersslpeeosglcpselteevsmhatetiiaogicotxfretnrifneihrlhateihsnefttiaece'
+&gt;&gt;&gt; railfence_encipher('hellothereavastmeheartiesthisisalongpieceoftextfortestingrailfenceciphers', 5)
+'hresleogcseeemhetaocofrnrnerlhateihsnefttiaeceltvsatiigitxetifihoarspeslp'
+&gt;&gt;&gt; railfence_encipher('hellothereavastmeheartiesthisisalongpieceoftextfortestingrailfenceciphers', 7)
+'haspolsevsetgifrifrlatihnettaeelemtiocxernhorersleesgcptehaiaottneihesfic'
+</code></pre></div>
+<details class="source">
+<summary>
+<span>Expand source code</span>
+</summary>
+<pre><code class="python">def railfence_encipher(message, height, fillvalue=&#39;&#39;):
+    &#34;&#34;&#34;Railfence cipher.
+    Works by splitting the text into sections, then reading across them to
+    generate the rows in the cipher. The rows are then combined to form the
+    ciphertext.
+
+    Example: the plaintext &#34;hellotherefriends&#34;, with a height of four, written 
+    out in the railfence as 
+       h h i
+       etere*
+       lorfns
+       l e d
+    (with the * showing the one character to finish the last section). 
+    Each &#39;section&#39; is two columns, but unfolded. In the example, the first
+    section is &#39;hellot&#39;.
+
+    &gt;&gt;&gt; railfence_encipher(&#39;hellothereavastmeheartiesthisisalongpieceoftextfortestingrailfenceciphers&#39;, 2, fillvalue=&#39;!&#39;)
+    &#39;hlohraateerishsslnpeefetotsigaleccpeselteevsmhatetiiaogicotxfretnrifneihr!&#39;
+    &gt;&gt;&gt; railfence_encipher(&#39;hellothereavastmeheartiesthisisalongpieceoftextfortestingrailfenceciphers&#39;, 3, fillvalue=&#39;!&#39;)
+    &#39;horaersslpeeosglcpselteevsmhatetiiaogicotxfretnrifneihr!!lhateihsnefttiaece!&#39;
+    &gt;&gt;&gt; railfence_encipher(&#39;hellothereavastmeheartiesthisisalongpieceoftextfortestingrailfenceciphers&#39;, 5, fillvalue=&#39;!&#39;)
+    &#39;hresleogcseeemhetaocofrnrner!!lhateihsnefttiaece!!ltvsatiigitxetifih!!oarspeslp!&#39;
+    &gt;&gt;&gt; railfence_encipher(&#39;hellothereavastmeheartiesthisisalongpieceoftextfortestingrailfenceciphers&#39;, 10, fillvalue=&#39;!&#39;)
+    &#39;hepisehagitnr!!lernesge!!lmtocerh!!otiletap!!tseaorii!!hassfolc!!evtitffe!!rahsetec!!eixn!&#39;
+    &gt;&gt;&gt; railfence_encipher(&#39;hellothereavastmeheartiesthisisalongpieceoftextfortestingrailfenceciphers&#39;, 3)
+    &#39;horaersslpeeosglcpselteevsmhatetiiaogicotxfretnrifneihrlhateihsnefttiaece&#39;
+    &gt;&gt;&gt; railfence_encipher(&#39;hellothereavastmeheartiesthisisalongpieceoftextfortestingrailfenceciphers&#39;, 5)
+    &#39;hresleogcseeemhetaocofrnrnerlhateihsnefttiaeceltvsatiigitxetifihoarspeslp&#39;
+    &gt;&gt;&gt; railfence_encipher(&#39;hellothereavastmeheartiesthisisalongpieceoftextfortestingrailfenceciphers&#39;, 7)
+    &#39;haspolsevsetgifrifrlatihnettaeelemtiocxernhorersleesgcptehaiaottneihesfic&#39;
+    &#34;&#34;&#34;
+    sections = chunks(message, (height - 1) * 2, fillvalue=fillvalue)
+    n_sections = len(sections)
+    # Add the top row
+    rows = [cat([s[0] for s in sections])]
+    # process the middle rows of the grid
+    for r in range(1, height-1):
+        rows += [cat([s[r:r+1] + s[height*2-r-2:height*2-r-1] for s in sections])]
+    # process the bottom row
+    rows += [cat([s[height - 1:height] for s in sections])]
+    # rows += [wcat([s[height - 1] for s in sections])]
+    return cat(rows)</code></pre>
+</details>
+</dd>
+<dt id="szyfrow.railfence.wcat"><code class="name flex">
+<span>def <span class="ident">wcat</span></span>(<span>iterable, /)</span>
+</code></dt>
+<dd>
+<div class="desc"><p>Concatenate any number of strings.</p>
+<p>The string whose method is called is inserted in between each given string.
+The result is returned as a new string.</p>
+<p>Example: '.'.join(['ab', 'pq', 'rs']) -&gt; 'ab.pq.rs'</p></div>
+</dd>
+</dl>
+</section>
+<section>
+</section>
+</article>
+<nav id="sidebar">
+<h1>Index</h1>
+<div class="toc">
+<ul></ul>
+</div>
+<ul id="index">
+<li><h3>Super-module</h3>
+<ul>
+<li><code><a title="szyfrow" href="index.html">szyfrow</a></code></li>
+</ul>
+</li>
+<li><h3><a href="#header-functions">Functions</a></h3>
+<ul class="two-column">
+<li><code><a title="szyfrow.railfence.cat" href="#szyfrow.railfence.cat">cat</a></code></li>
+<li><code><a title="szyfrow.railfence.lcat" href="#szyfrow.railfence.lcat">lcat</a></code></li>
+<li><code><a title="szyfrow.railfence.railfence_break" href="#szyfrow.railfence.railfence_break">railfence_break</a></code></li>
+<li><code><a title="szyfrow.railfence.railfence_decipher" href="#szyfrow.railfence.railfence_decipher">railfence_decipher</a></code></li>
+<li><code><a title="szyfrow.railfence.railfence_encipher" href="#szyfrow.railfence.railfence_encipher">railfence_encipher</a></code></li>
+<li><code><a title="szyfrow.railfence.wcat" href="#szyfrow.railfence.wcat">wcat</a></code></li>
+</ul>
+</li>
+</ul>
+</nav>
+</main>
+<footer id="footer">
+<p>Generated by <a href="https://pdoc3.github.io/pdoc"><cite>pdoc</cite> 0.9.2</a>.</p>
+</footer>
+</body>
+</html>
\ No newline at end of file