python crypto square

This commit is contained in:
Xevion
2020-11-14 09:22:27 -06:00
parent 9269a8f4bf
commit b6535bfbe2
4 changed files with 177 additions and 0 deletions

View File

@@ -0,0 +1 @@
{"track":"python","exercise":"crypto-square","id":"627b6abfc585457083648a1c000bf0ab","url":"https://exercism.io/my/solutions/627b6abfc585457083648a1c000bf0ab","handle":"Xevion","is_requester":true,"auto_approve":false}

View File

@@ -0,0 +1,122 @@
# Crypto Square
Implement the classic method for composing secret messages called a square code.
Given an English text, output the encoded version of that text.
First, the input is normalized: the spaces and punctuation are removed
from the English text and the message is downcased.
Then, the normalized characters are broken into rows. These rows can be
regarded as forming a rectangle when printed with intervening newlines.
For example, the sentence
```text
"If man was meant to stay on the ground, god would have given us roots."
```
is normalized to:
```text
"ifmanwasmeanttostayonthegroundgodwouldhavegivenusroots"
```
The plaintext should be organized in to a rectangle. The size of the
rectangle (`r x c`) should be decided by the length of the message,
such that `c >= r` and `c - r <= 1`, where `c` is the number of columns
and `r` is the number of rows.
Our normalized text is 54 characters long, dictating a rectangle with
`c = 8` and `r = 7`:
```text
"ifmanwas"
"meanttos"
"tayonthe"
"groundgo"
"dwouldha"
"vegivenu"
"sroots "
```
The coded message is obtained by reading down the columns going left to
right.
The message above is coded as:
```text
"imtgdvsfearwermayoogoanouuiontnnlvtwttddesaohghnsseoau"
```
Output the encoded text in chunks that fill perfect rectangles `(r X c)`,
with `c` chunks of `r` length, separated by spaces. For phrases that are
`n` characters short of the perfect rectangle, pad each of the last `n`
chunks with a single trailing space.
```text
"imtgdvs fearwer mayoogo anouuio ntnnlvt wttddes aohghn sseoau "
```
Notice that were we to stack these, we could visually decode the
ciphertext back in to the original message:
```text
"imtgdvs"
"fearwer"
"mayoogo"
"anouuio"
"ntnnlvt"
"wttddes"
"aohghn "
"sseoau "
```
## Exception messages
Sometimes it is necessary to raise an exception. When you do this, you should include a meaningful error message to
indicate what the source of the error is. This makes your code more readable and helps significantly with debugging. Not
every exercise will require you to raise an exception, but for those that do, the tests will only pass if you include
a message.
To raise a message with an exception, just write it as an argument to the exception type. For example, instead of
`raise Exception`, you should write:
```python
raise Exception("Meaningful message indicating the source of the error")
```
## Running the tests
To run the tests, run the appropriate command below ([why they are different](https://github.com/pytest-dev/pytest/issues/1629#issue-161422224)):
- Python 2.7: `py.test crypto_square_test.py`
- Python 3.4+: `pytest crypto_square_test.py`
Alternatively, you can tell Python to run the pytest module (allowing the same command to be used regardless of Python version):
`python -m pytest crypto_square_test.py`
### Common `pytest` options
- `-v` : enable verbose output
- `-x` : stop running tests on first failure
- `--ff` : run failures from previous test before running other test cases
For other options, see `python -m pytest -h`
## Submitting Exercises
Note that, when trying to submit an exercise, make sure the solution is in the `$EXERCISM_WORKSPACE/python/crypto-square` directory.
You can find your Exercism workspace by running `exercism debug` and looking for the line that starts with `Workspace`.
For more detailed information about running tests, code style and linting,
please see [Running the Tests](http://exercism.io/tracks/python/tests).
## Source
J Dalbey's Programming Practice problems [http://users.csc.calpoly.edu/~jdalbey/103/Projects/ProgrammingPractice.html](http://users.csc.calpoly.edu/~jdalbey/103/Projects/ProgrammingPractice.html)
## Submitting Incomplete Solutions
It's possible to submit an incomplete solution so you can see how others have completed the exercise.

View File

@@ -0,0 +1,18 @@
import math, string
def cipher_text(plain_text):
# Normalize the input
translation = str.maketrans({k : '' for k in string.punctuation})
plain_text = plain_text.translate(translation).replace(' ', '').lower()
if len(plain_text) == 0: return ''
# Calculate the dimensions of the crypto square (rectangle)
columns, matrix = math.ceil(math.sqrt(len(plain_text))), []
rows = math.ceil(len(plain_text) / columns)
for row in range(rows):
# Calculate the indexes
start, end = (row * columns), (row * columns) + columns
# Add pieces of the matrix, adding trailing space padding
matrix.append(plain_text[start:end].ljust(columns))
# Rotate the matrix so you can read by column
matrix = list(zip(*matrix))
return ' '.join(''.join(column) for column in matrix)

View File

@@ -0,0 +1,36 @@
import unittest
from crypto_square import cipher_text
# Tests adapted from `problem-specifications//canonical-data.json` @ v3.2.0
class CryptoSquareTest(unittest.TestCase):
def test_empty_string(self):
self.assertEqual(cipher_text(''), '')
def test_lowercase(self):
self.assertEqual(cipher_text('A'), 'a')
def test_remove_spaces(self):
self.assertEqual(cipher_text(' b '), 'b')
def test_remove_punctuation(self):
self.assertEqual(cipher_text('@1,%!'), '1')
def test_9chars_results_3chunks(self):
self.assertEqual(cipher_text('This is fun!'), 'tsf hiu isn')
def test_8chars_results_3chunks_ending_space(self):
self.assertEqual(cipher_text('Chill out.'), 'clu hlt io ')
def test_54chars_results_7chunks_2ending_space(self):
self.assertEqual(
cipher_text('If man was meant to stay on the ground, '
'god would have given us roots.'),
'imtgdvs fearwer mayoogo anouuio ntnnlvt wttddes aohghn sseoau '
)
if __name__ == '__main__':
unittest.main()