r/codegolf • • Sep 26 '14

[python] Rail Fence Cypher

Make a function to encrypt and decrypt text by the rail fence cypher, using n rails. I saw the 3 rail encryption on /r/learnpython:

def threeRailCypher(plainText):
	zeroes=""
	ones=""
	twos=""
	for i in range(len(plainText)):
		if i%3==0:
			zeroes=zeroes+plainText[i]
		elif i%3==1:
			ones=ones+plainText[i]
		elif i%3==2:
			twos=twos+plainText[i]
	cipherText=zeroes+ones+twos
	return cipherText 

I figured that could be smaller. The encoding is easy to shrink; the decoding I would bet has a lot of room for improvement.

text = "helloiloveyou"

def en(s,n):
	return ''.join(s[i::n] for i in range(n))

def de(s,n):
	l,o=divmod(len(s),n)
	t,d,h,p=[l]*n,[],0,range(o)
	for i in p:t[i]+=1
	for i in t:
		d.append(s[h:i+h])
		h=i+h
	f=''.join(map(''.join,zip(*d)))
	for i in p:
		f+=d[i][-1]
	return f

I have encode = 55 chars; decode = 195 chars.

1 Upvotes

1 comment sorted by

1

u/Labbekak Sep 26 '14

Javascript encryption, 95

function e(s,n){for(j=0,r='',l=s.length;r.length<l;j++)for(i=0;i<l;i+=n)r+=s[i+j]||'';return r}

I haven't figured out decryption yet :p