Hey guys, need a little bet of help with a comp sci assignment. Question 2 110 m
ID: 3701564 • Letter: H
Question
Hey guys, need a little bet of help with a comp sci assignment.
Question 2 110 marks]: In this question, you will write a program to encrypt and decrypt a string using a simple substitution cipher. In particular, you will start by setting up an alphabet string "abcdefghijklmnopgrstuvwxyz" (note there is a space character at the end of this string) Next, input an offset and a phrase (another string) to be encrypted. The characters in the phrase must be characters from the alphabet that you defined above. The offset indicates how to encrypt each character. In particular, each character will be replaced in the new encrypted string by a character that is "offset" number of characters beyond it in the alphabet. If a character in the input string is "c" and the offset is 2 then the character in the encrypted string will be "e" (which occurs 2 letters later in the alphabet). Note that you need to handle 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. You can assume that the offset will be less than the number of characters in the alphabet. The encryption problem is divided into three parts. The fourth part is to reverse this process and therefore create a function to decrypt a string To begin, set up your main program as the following #Main Program alpha = "abcdefghijklmnopqrstuvwxyz " offsetint (input ("Enter the offset: ")) phrase -input ("Enter the phrase to encrypt:")Explanation / Answer
# Hello World program in Python
print "Hello World! "
text = "abcdefghijklmnopqrstuvwxyz "
phrase = "Hello World"
print phrase
def findPos(A,ch):
pos = A.find(ch)
return pos
findPos(phrase,'o')
def findAltChar(A,pos1,cnt):
ind = (pos1 + cnt)%(len(A))
return A[ind]
#print("Contain Distance is: "+A[ind])
findAltChar(phrase,2,10)
def encrypt(A,P,Off):
newP = ""
for i in P:
#print " index " + i
#print findPos(A,i)
newP += findAltChar(A,findPos(A,i),Off)
print ("newP " + newP)
return newP
encrypt(text,"hello world",5)
def findAltDecryptChar(A,pos1,cnt):
ind = (pos1 - cnt)
if ind < 0 :
temp = len(A) + ind
else :
temp = ind
#print "temp in dec"
#print temp
return A[temp]
def decrypt(A,ephrase,eoff):
newP = ""
for i in ephrase:
print " index " + i
print findPos(A,i)
newP += findAltDecryptChar(A,findPos(A,i),eoff)
#print ("newP " + newP)
decrypt(text,"mjqqteatwqi",5)