Skip to content

Instantly share code, notes, and snippets.

@marskar
Last active September 27, 2019 04:25
Show Gist options
  • Save marskar/b01e3624d0f9c9f5b7edd5fa50946326 to your computer and use it in GitHub Desktop.
Save marskar/b01e3624d0f9c9f5b7edd5fa50946326 to your computer and use it in GitHub Desktop.
A Python function to perform rot13 encoding
from this import s
# Without long strings
def rot13(x):
abc = "".join(map(chr, range(65, 91)))
a_to_m = x in abc[:13] + abc[:13].lower()
n_to_z = x in abc[13:] + abc[13:].lower()
return chr(ord(x) + 13 * (a_to_m or -n_to_z))
# With long strings
def rot13(x):
a_to_m = x in "abcdefghijklmABCDEFGHIJKLM"
n_to_z = x in "nopqrstuvwxyzNOPQRSTUVWXYZ"
return chr(ord(x) + 13 * (a_to_m or -n_to_z))
# With a dictionary comprehension
def rot13(x):
return {chr(i + c): chr((i + 13) % 26 + c) for i in range(26) for c in (65, 97)}.get(x, x)
# My second favorite
def rot13(x):
if x.isalpha():
start = 65 if x.isupper() else 97
shift = (ord(x) - start + 13) % 26
return chr(start + shift)
return x
# My favorite
def rot13(x):
if x.isalpha():
shift = 13 if "a" <= x.lower() <= "m" else -13
return chr(ord(x) + shift)
return x
# No variables
def rot13(x):
if x.isalpha():
return chr(ord(x) + (13 if "a" <= x.lower() <= "m" else -13))
return x
# All on one line
def rot13(x):
return chr(ord(x) + (13 if "a" <= x.lower() <= "m" else -13)) if x.isalpha() else x
"".join(map(rot13, s))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment