Exercism v3 launches on Sept 1st 2021. Learn more! ๐๐๐

# rootulp's solution

## to Rail Fence Cipher in the Python Track

Published at Jul 13 2018 · 0 comments
Instructions
Test suite
Solution

#### Note:

This solution was written on an old version of Exercism. The tests below might not correspond to the solution code, and the exercise may have changed since this code was written.

Implement encoding and decoding for the rail fence cipher.

The Rail Fence cipher is a form of transposition cipher that gets its name from the way in which it's encoded. It was already used by the ancient Greeks.

In the Rail Fence cipher, the message is written downwards on successive "rails" of an imaginary fence, then moving up when we get to the bottom (like a zig-zag). Finally the message is then read off in rows.

For example, using three "rails" and the message "WE ARE DISCOVERED FLEE AT ONCE", the cipherer writes out:

``````W . . . E . . . C . . . R . . . L . . . T . . . E
. E . R . D . S . O . E . E . F . E . A . O . C .
. . A . . . I . . . V . . . D . . . E . . . N . .
``````

Then reads off:

``````WECRLTEERDSOEEFEAOCAIVDEN
``````

To decrypt a message you take the zig-zag shape and fill the ciphertext along the rows.

``````? . . . ? . . . ? . . . ? . . . ? . . . ? . . . ?
. ? . ? . ? . ? . ? . ? . ? . ? . ? . ? . ? . ? .
. . ? . . . ? . . . ? . . . ? . . . ? . . . ? . .
``````

The first row has seven spots that can be filled with "WECRLTE".

``````W . . . E . . . C . . . R . . . L . . . T . . . E
. ? . ? . ? . ? . ? . ? . ? . ? . ? . ? . ? . ? .
. . ? . . . ? . . . ? . . . ? . . . ? . . . ? . .
``````

Now the 2nd row takes "ERDSOEEFEAOC".

``````W . . . E . . . C . . . R . . . L . . . T . . . E
. E . R . D . S . O . E . E . F . E . A . O . C .
. . ? . . . ? . . . ? . . . ? . . . ? . . . ? . .
``````

Leaving "AIVDEN" for the last row.

``````W . . . E . . . C . . . R . . . L . . . T . . . E
. E . R . D . S . O . E . E . F . E . A . O . C .
. . A . . . I . . . V . . . D . . . E . . . N . .
``````

If you now read along the zig-zag shape you can read the original message.

## 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:

``````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):

• Python 2.7: `py.test rail_fence_cipher_test.py`
• Python 3.4+: `pytest rail_fence_cipher_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 rail_fence_cipher_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/rail-fence-cipher` 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 the help page.

## Submitting Incomplete Solutions

It's possible to submit an incomplete solution so you can see how others have completed the exercise.

### rail_fence_cipher_test.py

``````import unittest

from rail_fence_cipher import encode, decode

# Tests adapted from `problem-specifications//canonical-data.json` @ v1.1.0

class RailFenceCipherTest(unittest.TestCase):
def test_encode_with_two_rails(self):
self.assertMultiLineEqual(
encode('XOXOXOXOXOXOXOXOXO', 2), 'XXXXXXXXXOOOOOOOOO')

def test_encode_with_three_rails(self):
self.assertMultiLineEqual(
encode('WEAREDISCOVEREDFLEEATONCE', 3),
'WECRLTEERDSOEEFEAOCAIVDEN')

def test_encode_with_ending_in_the_middle(self):
self.assertMultiLineEqual(encode('EXERCISES', 4), 'ESXIEECSR')

def test_decode_with_three_rails(self):
self.assertMultiLineEqual(
decode('TEITELHDVLSNHDTISEIIEA', 3), 'THEDEVILISINTHEDETAILS')

def test_decode_with_five_rails(self):
self.assertMultiLineEqual(
decode('EIEXMSMESAORIWSCE', 5), 'EXERCISMISAWESOME')

def test_decode_with_six_rails(self):
self.assertMultiLineEqual(
decode(
'133714114238148966225439541018335470986172518171757571896261',
6),
'112358132134558914423337761098715972584418167651094617711286')

if __name__ == '__main__':
unittest.main()``````
``````class Rails:

def __init__(self, num_rails):
self.num_rails = num_rails
self.rails = [[] for _ in xrange(num_rails)]

def populate_rails_linear(self, message, rail_lengths):
message_list = list(message)
for rail in self.linear_iterator(rail_lengths):
rail.append(message_list.pop(0))

def populate_rails_zig_zag(self, message):
message_list = list(message)
for rail in self.zig_zag_iterator(message):
rail.append(message_list.pop(0))

def to_string_linear(self):
return ''.join([data for rail in self.rails for data in rail])

def to_string_zig_zag(self, message):
return ''.join([rail.pop(0) for rail in self.zig_zag_iterator(message)])

def linear_iterator(self, rail_lengths):
for index in xrange(len(self.rails)):
for rail_length in xrange(rail_lengths[index]):
yield self.rails[index]

def zig_zag_iterator(self, message):
index = 0
increasing = True
for _ in message:
yield self.rails[index]
increasing = self.direction(index, increasing)
index = self.increment_index(index, increasing)

def increment_index(self, index, increasing):
if increasing:
return index + 1
else:
return index - 1

def direction(self, index, increasing):
if index == 0:
return True
elif index == self.num_rails - 1:
return False
else:
return increasing

def encode(message, num_rails):
rails = Rails(num_rails)
rails.populate_rails_zig_zag(message)
return rails.to_string_linear()

def decode(message, num_rails):
faulty_rails = Rails(num_rails)
faulty_rails.populate_rails_zig_zag(message)
rail_lengths = [len(rail) for rail in faulty_rails.rails]

rails = Rails(num_rails)
rails.populate_rails_linear(message, rail_lengths)
return rails.to_string_zig_zag(message)``````

## Community comments

Find this solution interesting? Ask the author a question to learn more.

### What can you learn from this solution?

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.

• What compromises have been made?
• Are there new concepts here that you could read more about to improve your understanding?