In the rail fence cipher (also called zigzag cipher), the letters of the plaintext are initially written downwards and diagonally on successive "rails" of an imaginary fence, and then moving up after the bottom rail has been reached. When the top rail is reached, the message is again written downwards until the whole plaintext is written out.

If the text

And now for something completely different.

is written as such across four rails, we get the following result

A#####w#####s#####i#####m#####l#####f#####.
#n###o# ### #o###h#n###o#p###e#y###f#e###t#
##d#n###f#r###m#t###g#c###l#t### #i###r#n##
### #####o#####e##### #####e#####d#####e###

The encoded message is then formed by reading the letters on each rail from left to right, and going through the rails top to bottom. The encoded message for the above example thus reads as

Awsimlf.no  ohnopeyfetdnfrmtgclt irn oe ede

Assignment

Example

>>> encode('And now for something completely different.', 1)
'And now for something completely different.'
>>> encode('And now for something completely different.', 2)
'Adnwfrsmtigcmltl ifrn.n o o oehn opeeydfeet'
>>> encode('And now for something completely different.', 3)
'Anfstgmt fnn o o oehn opeeydfeetdwrmicllir.'
>>> encode('And now for something completely different.', 4)
'Awsimlf.no  ohnopeyfetdnfrmtgclt irn oe ede'
>>> encode('And now for something completely different.', 5)
'Aftm nn oehopydetdwrmicllir. o on eefensgtf'

>>> decode('And now for something completely different.', 1)
'And now for something completely different.'
>>> decode('Adnwfrsmtigcmltl ifrn.n o o oehn opeeydfeet', 2)
'And now for something completely different.'
>>> decode('Anfstgmt fnn o o oehn opeeydfeetdwrmicllir.', 3)
'And now for something completely different.'
>>> decode('Awsimlf.no  ohnopeyfetdnfrmtgclt irn oe ede', 4)
'And now for something completely different.'
>>> decode('Aftm nn oehopydetdwrmicllir. o on eefensgtf', 5)
'And now for something completely different.'

Epilogue

“The Fence”

There was a fence with spaces you
Could look through if you wanted to.

An architect who saw this thing
Stood there one summer evening,

Took out the spaces with great care
And built a castle in the air.

The fence was utterly dumbfounded:
Each post stood there with nothing round it.

A sight most terrible to see.
(They charged it with indecency.)

The architect then ran away
To Afric- or Americ-ay.

— Christian Morgenstern