ภาพรวม
วนลูปหาสตริงที่มีจำนวนสระ (a, e, i, o, u) มากที่สุด
ตัวอย่างโค้ด (แก้ไขจากต้นฉบับที่มี bug)
my_list = ["this", "week", "is", "going", "great"]
print("The list is:", my_list)
vowels = set('aeiouAEIOU')
max_vowel_count = -1
max_vowel_word = ""
for word in my_list:
vowel_count = sum(1 for char in word if char in vowels)
if vowel_count > max_vowel_count:
max_vowel_count = vowel_count
max_vowel_word = word
print("The result is:", max_vowel_word)
print(f"Vowel count: {max_vowel_count}")
ผลลัพธ์
The list is: ['this', 'week', 'is', 'going', 'great']
The result is: going
Vowel count: 2
คำอธิบาย (และแก้ไข bug ต้นฉบับ)
- โค้ดต้นฉบับมี bug: ใช้ตัวแปร
elementทับซ้อนใน nested comprehension ทำให้ผลลัพธ์ผิด (ได้ 'k') - "going" มีสระ o, i = 2 ตัว (มากที่สุด)
- "great" มี e, a = 2 ตัว (เท่ากัน แต่อันแรกชนะ)
เวอร์ชันสั้นๆ
vowels = set('aeiouAEIOU')
result = max(my_list, key=lambda w: sum(1 for c in w if c in vowels))
print(result) # going
Case Insensitive
ใช้ char.lower() in vowels หรือกำหนด vowels รวม uppercase