Done challenge 4
[cipher-challenge.git] / 2021 / 2021-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.3'
9 jupytext_version: 1.11.1
10 kernelspec:
11 display_name: Python 3 (ipykernel)
12 language: python
13 name: python3
14 ---
15
16 ```python Collapsed="false"
17 from szyfrow.caesar import *
18 from szyfrow.affine import *
19 from szyfrow.keyword_cipher import *
20 from szyfrow.support.text_prettify import *
21 ```
22
23 ```python Collapsed="false"
24 challenge_number = 4
25 plaintext_a_filename = f'plaintext.{challenge_number}a.txt'
26 plaintext_b_filename = f'plaintext.{challenge_number}b.txt'
27 ciphertext_a_filename = f'ciphertext.{challenge_number}a.txt'
28 ciphertext_b_filename = f'ciphertext.{challenge_number}b.txt'
29 ```
30
31 ```python Collapsed="false"
32 ca = open(ciphertext_a_filename).read()
33 cb = open(ciphertext_b_filename).read()
34
35 sca = sanitise(ca)
36 scb = sanitise(cb)
37 ```
38
39 ```python
40 (word_a, wrap_a), score_a = keyword_break(sca)
41 print(word_a, wrap_a, '\n')
42 pa = keyword_decipher(ca, word_a, wrap_a)
43 print(pa)
44 ```
45
46 ```python
47 pa = keyword_decipher(sca, word_a, wrap_a)
48 print(prettify(pa))
49 ```
50
51 ```python Collapsed="false"
52 open(plaintext_a_filename, 'w').write(prettify(pa))
53 ```
54
55 ```python
56 morse_chars = 'a b c d e f g h i j k l m n o p q r s t u v w x y z 0 1 2 3 4 5 6 7 8 9'.split()
57 # morse_chars
58 ```
59
60 ```python
61 morse_codes = '.- / -... / -.-. / -.. / . / ..-. / --. / .... / .. / .--- / -.- / .-.. / -- / -. / --- / .--. / --.- / .-. / ... / - / ..- / ...- / .-- / -..- / -.-- / --.. / ----- / .---- / ..--- / ...-- / ....- / ..... / -.... / --... / ---.. / ----.'.split(' / ')
62 ```
63
64 ```python
65 char_to_morse = {l: c for l, c in zip(morse_chars, morse_codes)}
66 morse_to_char = {c: l for l, c in zip(morse_chars, morse_codes)}
67 [char_to_morse[l] for l in 'abc']
68 ```
69
70 ```python
71 morse_table = ''.maketrans('AD', '.-')
72 cb_dd = cb.translate(morse_table)
73 cb_words = cb_dd.split(' / ')
74 cb_letters = cat(cat(morse_to_char[l] for l in w.split()) for w in cb_words)
75 cb_letters
76 ```
77
78 ```python
79 (word_b, wrap_b), score_a = keyword_break(cb_letters, fitness=Ptrigrams)
80 print(word_b, wrap_b, '\n')
81 pb = keyword_decipher(cb_letters, word_b, wrap_b)
82 print(prettify(pb))
83 ```
84
85 ```python Collapsed="false"
86 open(plaintext_b_filename, 'w').write(prettify(pb))
87 ```
88
89 ```python Collapsed="false"
90
91 ```