Last active
May 5, 2023 17:06
-
-
Save Rainyan/a9e3582466ead30c83a586bfe8db2763 to your computer and use it in GitHub Desktop.
ROT-n cipher in Python 3, defaulting as ROT-13
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from string import ascii_lowercase, ascii_uppercase | |
# Note that this already exists in Python as codecs.encode("text", "rot13") | |
# so you'd probably wanna use that instead of this implementation, | |
# unless you need a rotation of n places with n != 13. | |
def rot(text, rotation=13): | |
"""ROT-n cipher. | |
Decode by running the output through the function again | |
(assuming the rotation is exactly half of the used character set).""" | |
result = "" | |
for char in text: | |
if char.islower(): | |
charset = ascii_lowercase | |
else: | |
charset = ascii_uppercase | |
pos = charset.find(char) | |
if pos == -1: | |
result += char # Not in charset? Append as-is. | |
continue | |
pos = (pos + rotation) % len(charset) | |
result += charset[pos] | |
return result | |
assert rot("foobar") == "sbbone" | |
assert rot("sbbone") == "foobar" | |
assert rot(rot("foobar")) == "foobar" | |
assert rot("Abc!") == "Nop!" | |
assert rot("Nop!") == "Abc!" | |
assert rot(rot("Abc!")) == "Abc!" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment