[Leet Code] Goat Latin
S is given, composed of words separated by spaces. Each word consists of lowercase and uppercase letters only.
We would like to convert the sentence to “Goat Latin” (a made-up language similar to Pig Latin.)
The rules of Goat Latin are as follows:
- If a word begins with a vowel (a, e, i, o, or u), append
"ma"to the end of the word.
For example, the word 'apple' becomes 'applema'.
- If a word begins with a consonant (i.e. not a vowel), remove the first letter and append it to the end, then add
For example, the word
- Add one letter
'a'to the end of each word per its word index in the sentence, starting with 1.
For example, the first word gets
"a"added to the end, the second word gets
"aa"added to the end and so on.
Return the final sentence representing the conversion from
S to Goat Latin.
Input: "I speak Goat Latin"
Output: "Imaa peaksmaaa oatGmaaaa atinLmaaaaa"
Input: "The quick brown fox jumped over the lazy dog"
Output: "heTmaa uickqmaaa rownbmaaaa oxfmaaaaa umpedjmaaaaaa overmaaaaaaa hetmaaaaaaaa azylmaaaaaaaaa ogdmaaaaaaaaaa"
def toGoatLatin(self, S):
:type S: str
lst = S.split(" ")
answer = ""
vowels = ["a", "e", "i", "o", "u"]
for i, v in enumerate(lst):
if v.lower() not in vowels:
first_letter = v
lst[i] = v[1:] + first_letter
lst[i] += "ma"
lst[i] += 'a' * (i + 1)
answer += lst[i] + " "
First we split the string into a list, then we create the answer variable. The vowels list will allow us to check whether a vowel is at the start or of the word or not. We enumerate through the list. This will give us the value and the index that the value is at. We check the value, v, its first letter, to check if it’s a vowel or consonant. If it’s a consonant, we take the first letter and assign it in memory to first_letter, then we shorten the value of the variable from the first index, to the second, taking away the first letter, and then we add on the first_letter variable so that it’s at the end of the word. Then we carry on as if it was a vowel, as both have the same procedure from here on. We add “ma” to the end of the word, and then we add the amount of ‘a’s to the value of the index + 1 (as the index will start at 0). Lastly, we add the list item to the answer string, then finally, we return the string with the strip method as this will take away the whitespace at the end.