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

โปรแกรมคำนวณคะแนนคำจากรายการคำใน Python

การคำนวณคะแนนคำตามจำนวนสระ

กำหนดรายการคำ (พิมพ์เล็ก) คำนวณคะแนน: สระ = [a,e,i,o,u,y]

  • จำนวนสระเป็นเลขคู่ → คะแนน 2
  • จำนวนสระเป็นเลขคี่ → คะแนน 1
  • คะแนนรวม = ผลรวมคะแนนทุกคำ

ตัวอย่างโค้ด

def solve(words):
    score = 0
    for word in words:
        num_vowels = 0
        for letter in word:
            if letter in ['a', 'e', 'i', 'o', 'u', 'y']:
                num_vowels += 1
        if num_vowels % 2 == 0:
            score += 2
        else:
            score += 1
    return score

words = ["programming", "science", "python", "website", "sky"]
print(solve(words))

ผลลัพธ์

6

รายละเอียดคะแนน

  • programming: o,a,i → 3 สระ (คี่) → 1
  • science: i,e,e → 3 สระ (คี่) → 1
  • python: o,o → 2 สระ (คู่) → 2
  • website: e,i,e → 3 สระ (คี่) → 1
  • sky: y → 1 สระ (คี่) → 1
  • รวม: 1+1+2+1+1 = 6