In: Computer Science
IN PYTHON
1) Pig Latin
Write a function called igpay(word) that takes in a string word representing a word in English, and returns the word translated into Pig Latin. Pig Latin is a “language” in which English words are translated according to the following rules:
For any word that begins with one or more consonants: move the consonants to the end of the word and append the string ‘ay’.
For all other words, append the string ‘way’ to the end.
For the above you can assume that ‘a’, ‘e’, ‘i’, ‘o’, and ‘u’ are vowels, and any other letter is a consonant. This does mean that ‘y’ is considered a consonant even in situations where it really shouldn’t be.
For this exercise, you can assume the following:
There will be no punctuation.
All letters will be lowercase
Every word will have at least one vowel (so we won’t give you a word like “by”)
Write a helper function that finds the index of the first vowel in a given word, and use that in your main function.
Hints:
To find the index of the first vowel in a given word, since you’re interested in the indexes, looping through the indexes of the string using range, or enumerate, or a while loop may work better than a direct for loop on the characters.
Use slicing to break up the string into all of the letters before the vowel, and all of the letters from the vowel onwards.
Examples:
>>> igpay('can')
'ancay'
>>> igpay('answer')
'answerway'
>>> igpay('prepare')
'eparepray'
>>> igpay('synthesis')
'esissynthay'
CODE:
def first_vowel(word): # A HELPER FUNCTION WHICH RETURNS THE INDEX OF FIRST VOWEL IN THE WORD
vowels = "aeiou" # STORED THE VOWELS IN A STRING VARIABLE VOWELS
for index,value in enumerate(word): # ENUMERATE FUNCTION DOES THE INDEXING FOR THE WORD, FOR EX. ENUMERATE("HELLO") = [(0, 'H'), (1, 'e'), (2, 'l'), (3, 'l'), (4, 'o')] MEANS THE FIRST VALUE IS INDEX AND 2ND VALUE IS THE VALUE AT THAT INDEX
if value in vowels: # CHECK IF VALUE IS IN VOWELS, THEN RETURN INDEX ELSE DO NOTHING, IN LAST IF VOWEL NOT FOUND RETURN -1
return index
return -1
def igpay(word): # FUNCTION WHICH RETURNS THE STRING TRANSLATED TO PIG LATIN
index = first_vowel(word) # FIND THE INDEX OF FIRST VOWEL
res = "" # INITIALIZE THE RESULTANT STRING RES WITH EMPTY STRING
if index>0: # IF INDEX IS GREATER THAN 0 THAT MEANS WORD START WITH A CONSONANT
res+=word[index:]+word[:index]+"ay" # ASSIGN ALL THE LETTERS FROM INDEX TO LAST, AND CONCATENATE AFTER START TO INDEX AND IN LAST AY
elif index==0: # IF INDEX IS 0 THAT MEANS WORD STARTS WITH A VOWEL
res+=word+"way" # SO JUST CONCATENATE WAY IN THE LAST OF THE WORD
return res # RETURN THE RESULTANT STRING
# SAMPLE INPUT
print(igpay('can'))
print(igpay('answer'))
print(igpay('prepare'))
print(igpay('synthesis'))
OUTPUT:
ancay
answerway
eparepray
esissynthay
NOTE: If you have any queries regarding the solution, you may ask in the comment section. HAPPY LEARNING!!