Skip to content

Instantly share code, notes, and snippets.

@minte9
Last active June 2, 2021 17:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save minte9/7157c9390c9f6fe600721721c16e207d to your computer and use it in GitHub Desktop.
Save minte9/7157c9390c9f6fe600721721c16e207d to your computer and use it in GitHub Desktop.
Python / Language / Strings
# A Caesar cypher is a weak form on encryption
# It involves "rotating" each letter by a number (shift it through the alphabet)
# A rotated by 3 is D; Z rotated by 1 is A
# In a SF movie the computer is called HAL, which is IBM rotated by -1
# Write a function rotate_word()
# Use built-in functions ord (char to code_number), chr (codes to char)
# SOLUTION
def rotate(word, no):
rotated = ""
for i in range(len(word)):
char = ord(word[i]) + no
new = chr(char)
rotated = rotated + new
return rotated
print(rotate("abc", 1)) # bcd
print(rotate("abc", 3)) # def
print(rotate("IBM", -1)) # HAL
print(rotate("HAL", 1)) # IBM
print(rotate("Hello World", 13)) # Uryy|-d|yq
# EXTRA - DECRYPT (without cypher)
def decrypt(word, no):
return rotate(word, -no)
for i in range(26):
print(decrypt("Uryy|-d|yq", i))
"""
...
Jgnnq"Yqnf
Ifmmp!Xpme
Hello Wold
GdkknVnkc
...
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment