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

โปรแกรมตรวจสอบครึ่งสตริงว่ามีสระเท่ากันหรือไม่ (Python)

โจทย์

มีสตริง s ความยาวคู่ แบ่งครึ่งได้ a และ b ตรวจสอบว่าจำนวนสระ (a,e,i,o,u พิมพ์เล็ก/ใหญ่) ในทั้งสองครึ่งเท่ากันหรือไม่

ตัวอย่าง: s = "talent" → ครึ่ง: "tal" และ "ent" → สระแต่ละครึ่ง = 1 → True

อัลกอริธึม

  1. แบ่งสตริงครึ่ง
  2. นับสระในแต่ละครึ่ง
  3. เปรียบเทียบจำนวน

โค้ด Python


def solve(s):
    vowels = ['a','e','i','o','u','A','E','I','O','U']
    a = s[:len(s)//2]
    b = s[len(s)//2:]
    count1 = sum(1 for c in a if c in vowels)
    count2 = sum(1 for c in b if c in vowels)
    return count1 == count2

s = "talent"
print(solve(s))  # Output: True

Input / Output

Input:  "talent"
Output: True