The objectives of this lab are to gain more experience with the Python language,
ID: 3862270 • Letter: T
Question
The objectives of this lab are to gain more experience with the Python language, to work with strings, and write search algorithms. In this lab, you will write a program to encrypt a string using a simple substitution cipher. In particular, you will set up an alphabet string, say ”abcdefghijklmnopqrstuvwxyz ”. This should be assigned to a variable in your code. The program must be general enough that you or the TA can change the alphabet. Next input an offset and a phrase (string) to be encrypted. The characters in the phrase will be characters from the alphabet. The offset indicates how to encrypt each character. In particular, if a character in the string is ”c” and the offset is 2 then that character in the encrypt string is ”e” (which occurs 2 letters later in the alphabet). Note that you need to wrap-around at the end of the alphabet. For example, if a character in the input string is ”z”, then the encrypted character will be ”a” if the offset is 2. The encryption problem is divided into three parts. The fourth part, solving decryption, is optional. To begin, set up your main program with the following: alph a = ’ ’ abcde f ghi j klmn op q r s tu vw x yz ’ ’ o f f s e t = i n t ( i n p u t ( ’ ’ Enter the o f f s e t : ’ ’ ) ) ph r a se = i n p u t ( ’ ’ Enter the ph r a se t o e n c r y p t : ’ ’ ) Note t h a t t h e r e i s a sp a ce c h a r a c t e r a t the end o f the al p h a b e t s t r i n g s o t h a t you can i n cl u d e s p a c e s i n your p h r a s e s
You will also need to be able to find the letter that is a certain distance (number of letters) away from the position of another letter. Write a 1 function called findaltchar(A,pos1,cnt) that returns the letter that is offset cnt positions after the letter at position pos1 in alphabet A. For example, for the alphabet above, if pos1 is 7 and cnt is 3, then the function returns letter ”k”. Note, handle the wrap-around. Call this from your main program to test it
Explanation / Answer
alpha = "abcdefghijklmnopqrstuvwxyz "
dict_alpha = {}
for i in range(0, len(alpha)):
dict_alpha[alpha[i]] = i
def findaltchar(A,pos1,cnt):
pos = pos1 + cnt
if pos >= len(A):
pos = cnt - (len(A) - pos1)
return A[pos]
offset = int(input("Enter an offset for substitution cipher: "))
phrase = raw_input("Enter phrase to encrypt: ")
cipherList = []
for c in phrase:
cipherList.append(findaltchar(alpha, dict_alpha[c], offset))
cipher = "".join(cipherList)
print cipher
# link for code
https://goo.gl/FeAw4V
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.