2 posts tagged “algorithm”
Rewritten to make it more modular, basically works the same way as before.
import sys
alphabet = 'abcdefghijklmnopqrstuvwxyz'
balphabet = 'zyxwvutsrqponmlkjihgfedcba'
class LetterBack:
'''Class for Encrypting a string of letters'''
def __init__(self, text='mnm'):
self.text = text
def encrypt(self, aSentance):
'''Encrypts a given string by replacing each letter
with the letter before it in the alphabet.'''
output = ''
for element in aSentance:
for i in range(26):
if element == alphabet[i]:
output += alphabet[i-1]
print output
def decrypt(self, aSentance):
'''Decrypts a given string encoded by the encrypt
function.'''
output = ''
for element in aSentance:
#print element + ' this is 1'
for i in range(26):
if element == balphabet[i]:
output += balphabet[i-1]
print output
def main():
lb = LetterBack()
if sys.argv[1] == '-e':
lb.encrypt(sys.argv[2])
elif sys.argv[1] == '-d':
lb.decrypt(sys.argv[2])
if __name__ == '__main__':
main()
use:
python letterback.py -e 'alvin'
returns: zkuhm
python letterback.py -d 'zkuhm'
returns: alvin
or in the python interpreter:
>>> from letterback import LetterBack
>>> lb = LetterBack()
>>>lb.encrypt('alvin')
zkuhm
>>> lb.decrypt('zkuhm')
alvin
enjoy :)
I scripted this up really quick last night while my girlfriend and I were having fun sending cryptic messages to each other. Basically all it does is encode or decode a string of letters given as CLI arguments. The program takes a given string and prints out in place of each letter a letter before that letter in the alphabet. For example: a = z, b = a, and so on....
Here is a code:
#! /usr/bin/python
#
# Author: Alvin D. Morris
# Date: August 5, 2008
#
# Program for encrypting a string of text.
import sys
alphabet = 'abcdefghijklmnopqrstuvwxyz'
balphabet = 'zyxwvutsrqponmlkjihgfedcba'
def encrypt(aSentance):
'''Encrypts a given string by replacing each letter with the letter before it in the alphabet.'''
output = ''
for element in aSentance:
for i in range(26):
if element == alphabet[i]:
output += alphabet[i-1]
print output
def decrypt(aSentance):
'''Decrypts a given string encoded by the encrypt function.'''
output = ''
for element in aSentance:
#print element + ' this is 1'
for i in range(26):
if element == balphabet[i]:
output = output + balphabet[i-1]
print output
def main():
if sys.argv[1] == '-e':
encrypt(sys.argv[2])
elif sys.argv[1] == '-d':
decrypt(sys.argv[2])
if __name__ == '__main__':
main()
Usage:python back.py -e alvin
returns: zkuhm python back.py -d zkuhm
returns: alvin
