In: Computer Science
Use python write a function that translates the input string into Pig Latin. The translation should be done word by word, where all words will be separated by only one space. You may assume that each word must have at least one vowel (a,e,i,o,u and uppercased counterparts), and there will be no punctuation or other special characters in the input string.
The Pig Latin rules are as follows:
For words that begin with consonants, all letters before the initial vowel are placed at the end of the word sequence. Then, “ay” is added.
Example: “pig” -> “igpay”, “banana” -> “ananabay”, “duck” -> “uckday”,
“stupid” -> “upidstay”, “floor” -> “oorflay”, “string” -> “ingstray”.
For words that begin with vowels, append “yay” to the end of this word.
Example: “omelet” -> “omeletyay”, “eat” -> “eatyay”, “egg” -> “eggyay”.
For whatever reason, we are afraid of 8-letter words. Thus, whenever you encounter a word with 8 letters, you should stop translating immediately and return what we have translated so far.
Example: “A short sentence” -> “Ayay ortshay”
Hint: command in might be useful here
Hint: either break or continue may be helpful here. Think which one
Hint: the method enumerate() can be useful. A brief explanation and examples of its potential use can be found here.
def pig_latin(string):
"""
>>> pig_latin('Hi how are you')
'iHay owhay areyay ouyay'
>>> pig_latin('Absolute')
''
>>> pig_latin('When words begin with consonant clusters')
'enWhay ordsway eginbay ithway onsonantcay'
"""
Raw_code:
# pig_latin function defintion takes a string as parameter
def pig_latin(string):
# splitting the string into list of words at whitespace
characters
string = string.split()
# a vowels tuple for comparision
vowels = ("a", "e", "i", "o", "u")
# result variable for storing result string
result = ""
# for loop for iterating over each word in the string
for word in string:
# if word is of length 8 breaking the function by returning
result
if len(word) == 8:
return result
# using memebership operator and string index for checking
whether
#the first character is an vowel
elif word[0] in vowels or word[0].lower() in vowels:
result += word + "yay "
else:
# for loop for iterating over the characters in the word until it
reaches a vowel
for index, char in enumerate(word):
# using memebership operator and checking whether the character is
an vowel
if char in vowels or char.lower() in vowels:
# using string slicing for getting result string
# result is string from vowel to last + string form start to vowel
+ "ay "
result += word[index:] + word[:index] + "ay "
# breaking for loop for the word
break
# returning result
return result
print(pig_latin("Hi how are you"))
print(pig_latin("When words begin with consonant clusters"))
print(pig_latin("pig"))
print(pig_latin("banana"))
print(pig_latin("duck"))
print(pig_latin("stupid"))
print(pig_latin("floor"))
print(pig_latin("string"))
print(pig_latin("omelet"))
print(pig_latin("eat"))
print(pig_latin("egg"))