Skip to content

Instantly share code, notes, and snippets.

@alberthdev
Last active January 20, 2016 21:28
Show Gist options
  • Select an option

  • Save alberthdev/d38b7113db5b7c0cd91b to your computer and use it in GitHub Desktop.

Select an option

Save alberthdev/d38b7113db5b7c0cd91b to your computer and use it in GitHub Desktop.
Fun project solution from Brent!
#!/usr/bin/env python
# Secret Message Project from Brent Smith
# Solution by Albert Huang
# This is 100% public domain, use it for whatever you want.
#
# Python 3 stubs
try:
input = raw_input
except NameError:
pass
cipher_dict = {}
# Ask user for sentence!
sentence = input("Enter sentence to encrypt: ")
# Ask user for shift amount!
# Note - we assume the user will type a number!
shift = int(input("Enter shift value: "))
# Create our cipher dictionary!
# This is a nice, easy way to translate without going back and forth with ord()/chr()!
# Each key maps to the translated letter in the dictionary.
# The for loop goes across all of the letters - from 0 to 25.
# (0 -> 25 are offsets from the first letter, so at 0, we're dealing
# with 'a'/'A', 1 with 'b'/'B', etc. in ASCII.)
for x in range(0, 26):
# Set this lowercase letter to map to:
# the shifted letter IF it's still in our lowercase range
# ELSE do circular shift back!
cipher_dict[chr(65 + x)] = (chr(65 + x + shift) if (65 + x + shift) <= (65 + 25) else chr(65 + x + shift - 26))
# Set this uppercase letter to map to:
# the shifted letter IF it's still in our uppercase range
# ELSE do circular shift back!
cipher_dict[chr(97 + x)] = (chr(97 + x + shift) if (97 + x + shift) <= (97 + 25) else chr(97 + x + shift - 26))
# Encode our phrase using the dictionary:
encoded = ""
# Loop through each letter in the sentence!
for l in sentence:
# Use the cipher dict to translate
# IF it's a letter
# ELSE don't translate it!
encoded += (cipher_dict[l] if l.isalpha() else l)
# Print our result!
print("The encoded phrase is: " + encoded)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment