-1

I'm kinda new to python and I'm wondering how I can turn this rot (n) encode function

def rot_encode(n):
    from string import ascii_lowercase as lc, ascii_uppercase as uc
    lookup = str.maketrans(lc + uc, lc[n:] + lc[:n] + uc[n:] + uc[:n])
    return lambda s: s.translate(lookup)

print(rot_alpha(13)('Hello World'))

To a decode function

I don't want to use the built-in functionality of python to encode or decode, I want to recreate it.

Thanks in advance

Roel Huizing
  • 3
  • 1
  • 3

1 Answers1

3

You don't have to recreate anything. Just shift the letters in the other direction, i.e. instead of rot_encode(13), call rot_encode(-13) to decode the previously encoded string.

x = rot_encode(13)('Hello World')
y = rot_encode(-13)(x)
print(x) # Uryyb Jbeyq
print(y) # Hello World

Of course, you can also wrap this into a rot_decode function if you prefer.

def rot_decode(n):
    return rot_encode(-n)
tobias_k
  • 81,265
  • 12
  • 120
  • 179
  • 1
    Addendum: Of course, in the special case of ROT13 not even this is necessary, as 13 is exactly the half of 26 (the letters in the alphabet), and thus encoding twice will also decode the string, i.e. `rot13(rot13(x)) == x`. – tobias_k Nov 30 '17 at 20:01