Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Goat Latin ใน Python

สมมติว่าเรามีชุดของสตริง (ประโยค) ในชุดนั้นมีหลายคำ แต่ละคำประกอบด้วยตัวอักษรพิมพ์เล็กและพิมพ์ใหญ่ ภารกิจของเราคือแปลงประโยคให้อยู่ในรูปแบบ Goat-Latin Goat Latin คล้ายกับ Pig Latin มีเงื่อนไขดังนี้:

  • ถ้าคำขึ้นต้นด้วยสระ ให้ต่อท้ายด้วย '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"