In: Computer Science
question: Pig LatinPig latin, is a mock language which
encrypts english sentences using the following rules: For every
word in a sentence, the firstletter of the word is shifted to the
end of the word and the suffix “-ay” is added at the end of the
word. For example, “hey pat”becomes “eyhay atpay”.Implement
thepiglatin(str)function so it translates sentences to pig latin.
If you have time remaining, try implementing afunction to ”decrypt”
piglatin, i.e. given a sentence in piglatin, return the english
version of the sentence
def pig_latin(sentence: str) -> str:
"""
Return a pig latin encrypted version of the
given sentence
>>> pig_latin("that pig is
so cute aww")
'hattay igpay siay osay utecay wwaay'
>>> pig_latin("utm needs
more food options")
'tmuay eedsnay oremay oodfay ptionsoay'
"""
# TODO: write this function's body - ay
pass
Code is well explained in comments=>
#This is Encryption Function
def pig_latin(sentence: str):
#sentence passed for encryption
list1=sentence.split(' ')
#split the sentence by space and store them in list
#as we have to encrypt each word in sentence
#Iteration of the list of sentence
for i in range(len(list1)):
prevStr=list1[i]
#store word in prevStr(temporary string) for encryption
updateStr=prevStr[1:]+prevStr[0]+"ay"
# as given in question we will take all character in word
#except 1st by using prevStr[1:] and put first letter of word
# after it by using prevStr[0] and at last add "ay" at the end
# finally store them in updateStr
list1[i]=updateStr
#once encrytion is done we will store updateStr in list of sentence
sentence=" ".join(list1)
#once complete list of sentence is encypted we will convert it
#into string of sentence by using join(by space)
return sentence
#This is decryption Function
def pig_latin_decryption(sentence: str):
#encrypted text passed for decryption
list1=sentence.split(' ')
#split the sentence by space and store them in list
#as we have to decrypt each word in encrypted text
#Iteration of the sentence list
for i in range(len(list1)):
prevStr=list1[i]
#store word in prevStr(temporary string) for decryption
updateStr=prevStr[-3]+prevStr[:len(prevStr)-3]
# By basic logics we will take last 3rd character in word
#by using prevStr[-3] and then add all characters of
#word except last three by using prevStr[:len(prevStr)-3]
# and finally store them in updateStr
list1[i]=updateStr
#once Decryption is completed we will convert it
#into string of sentence by using join(by space)
sentence=" ".join(list1)
return sentence
print("*****Encrypted Text*****")
print(pig_latin("that pig is so cute aww"))
print("*****Decrypted Text*****")
print(pig_latin_decryption("hattay igpay siay osay utecay wwaay"))
#some example
These code uses basic indexing and it is written for python 3.x.
In case of any doubt drop a comment