Python 中的山羊拉丁语


假设我们有一组字符串(句子),在这组字符串中有一些单词。每个单词都由小写字母和大写字母组成。我们的任务是将句子转换为山羊拉丁语形式。山羊拉丁语类似于猪拉丁语。有一些条件。

  • 如果单词以元音开头,则在单词后附加“ma”。
  • 如果单词以辅音开头,则将其从开头移除,并将其附加到末尾,然后在末尾添加“ma”。
  • 在每个单词的末尾添加一个字母“a”,每个单词的个数与其在句子中的单词索引相同,从 1 开始。

因此,如果示例类似于“Adam wants to go to the university”,则转换后的字符串将是“Adammaa antswmaaa otmaaaa ogmaaaaa otmaaaaaa hetmaaaaaaa universitymaaaaaaaa”。

要解决这个问题,任务很简单,获取句子并将其拆分为单词,然后对于每个单词,检查给定的条件并执行上述操作。

示例

让我们看看以下实现以获得更好的理解 -

 现场演示

class Solution:
   def toGoatLatin(self, S):
      """
      :type S: str
      :rtype: str
      """
      temp = S.split(" ")
      counter = 1
      result = []
      vowel = {"a","e","i","o","u"}
      for i in temp:
         if i[0].lower() in vowel:
            x = i + "ma" + ("a"*counter)
         else:
            x=i[1:]+i[0] + "ma" +("a"*counter)
         counter+=1
         result.append(x)
      return " ".join(c for c in result)
ob1 = Solution()
print(ob1.toGoatLatin("Adam wants to go to the university"))

输入

"Adam wants to go to the university"

输出

"Adammaa antswmaaa otmaaaa ogmaaaaa otmaaaaaa hetmaaaaaaa universitymaaaaaaaa"

更新于: 2020-04-28

492 次查看

开启你的职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.