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
"If man was meant to stay on the ground, god would have given us roots."
is normalized to:
The plaintext should be organized in to a rectangle. The size of the
r x c) should be decided by the length of the message,
c >= r and
c - r <= 1, where
c is the number of columns
r is the number of rows.
Our normalized text is 54 characters long, dictating a rectangle with
c = 8 and
r = 7:
"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:
Output the encoded text in chunks that fill perfect rectangles
(r X c),
c chunks of
r length, separated by spaces. For phrases that are
n characters short of the perfect rectangle, pad each of the last
chunks with a single trailing space.
"imtgdvs fearwer mayoogo anouuio ntnnlvt wttddes aohghn sseoau "
Notice that were we to stack these, we could visually decode the cyphertext back in to the original message:
"imtgdvs" "fearwer" "mayoogo" "anouuio" "ntnnlvt" "wttddes" "aohghn " "sseoau "
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:
raise Exception("Meaningful message indicating the source of the error")
To run the tests, run the appropriate command below (why they are different):
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
-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
Note that, when trying to submit an exercise, make sure the solution is in the
You can find your Exercism workspace by running
exercism debug and looking for the line that starts with
For more detailed information about running tests, code style and linting, please see the help page.
J Dalbey's Programming Practice problems http://users.csc.calpoly.edu/~jdalbey/103/Projects/ProgrammingPractice.html
It's possible to submit an incomplete solution so you can see how others have completed the exercise.
import unittest from crypto_square import encode # Tests adapted from `problem-specifications//canonical-data.json` @ v3.2.0 class CryptoSquareTest(unittest.TestCase): def test_empty_string(self): self.assertEqual(encode(''), '') def test_lowercase(self): self.assertEqual(encode('A'), 'a') def test_remove_spaces(self): self.assertEqual(encode(' b '), 'b') def test_remove_punctuation(self): self.assertEqual(encode('@1,%!'), '1') def test_9chars_results_3chunks(self): self.assertEqual(encode('This is fun!'), 'tsf hiu isn') def test_8chars_results_3chunks_ending_space(self): self.assertEqual(encode('Chill out.'), 'clu hlt io ') def test_54chars_results_7chunks_2ending_space(self): self.assertEqual( encode('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()
import string import math class CryptoSquare: @classmethod def encode(cls, msg): if len(cls.normalize(msg)) == 0: return '' return ' '.join(cls.transpose_square(cls.squarify(cls.normalize(msg)))) @classmethod def squarify(cls, msg): return [msg[i:i + cls.square_size(len(msg))] for i in range(0, len(msg), cls.square_size(len(msg)))] @staticmethod def transpose_square(square): return map(lambda *row: ''.join([ch if ch else '' for ch in row]), *square) @staticmethod def normalize(msg): return ''.join(ch.lower() for ch in msg if ch not in set(string.punctuation + ' ')) @staticmethod def square_size(msg_length): return int(math.ceil(msg_length**.5)) def encode(msg): return CryptoSquare.encode(msg)
A huge amount can be learned from reading other people’s code. This is why we wanted to give exercism users the option of making their solutions public.
Here are some questions to help you reflect on this solution and learn the most from it.