Updated for challenge 9
[cipher-tools.git] / 2020-early / 2020-a-challenge4.md
1 ---
2 jupyter:
3 jupytext:
4 formats: ipynb,md
5 text_representation:
6 extension: .md
7 format_name: markdown
8 format_version: '1.2'
9 jupytext_version: 1.3.4
10 kernelspec:
11 display_name: Python 3
12 language: python
13 name: python3
14 ---
15
16 ```python
17 import os,sys,inspect
18 currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
19 parentdir = os.path.dirname(currentdir)
20 sys.path.insert(0,parentdir)
21 ```
22
23 ```python
24 from cipher.caesar import *
25 from cipher.affine import *
26 from cipher.keyword_cipher import *
27
28 from support.text_prettify import *
29 from support.utilities import *
30 from support.plot_frequency_histogram import *
31 %matplotlib inline
32 ```
33
34 ```python
35 challenge_number = 4
36 plaintext_a_filename = f'{challenge_number}a.plaintext'
37 plaintext_b_filename = f'{challenge_number}b.plaintext'
38 ciphertext_a_filename = f'{challenge_number}a.ciphertext'
39 ciphertext_b_filename = f'{challenge_number}b.ciphertext'
40 ```
41
42 ```python
43 ca = open(ciphertext_a_filename).read()
44 cb = open(ciphertext_b_filename).read()
45
46 sca = sanitise(ca)
47 pca = letters(ca)
48 pta = depunctuate(ca)
49
50 scb = sanitise(cb)
51 pcb = letters(cb)
52 ptb = depunctuate(cb)
53 ```
54
55 ```python
56 kshifta, score = caesar_break(sca, fitness=Ptrigrams)
57 kshifta
58 ```
59
60 ```python
61 pa = caesar_decipher(sca, kshifta)
62 print(pa)
63 ```
64
65 ```python
66 fpa = lcat(tpack(segment(pa)))
67 print(fpa)
68 ```
69
70 ```python
71 open(plaintext_a_filename, 'w').write(fpa)
72 ```
73
74 ```python
75 fc = collections.Counter(scb)
76 plot_frequency_histogram(fc, sort_key=fc.get)
77 ```
78
79 ```python
80 (kwordb, kwrapb), score = keyword_break_mp(scb, fitness=Ptrigrams)
81 kwordb, kwrapb
82 ```
83
84 ```python
85 kwordb, score = simulated_annealing_break(scb, fitness=Ptrigrams)
86 kwordb
87 ```
88
89 ```python
90 print(keyword_decipher(cb, kwordb))
91 ```
92
93 ```python
94 pb = keyword_decipher(cb, 'heavywater', KeywordWrapAlphabet.from_last)
95 print(pb)
96 ```
97
98 ```python
99 open(plaintext_b_filename, 'w').write(pb)
100 ```
101
102 ```python
103 print(keyword_cipher_alphabet_of('heavywater', KeywordWrapAlphabet.from_last))
104 print(kwordb)
105 ```
106
107 ```python
108
109 ```