Python程式:從單詞列表中查詢單詞得分
假設我們有一個數組中包含一些單詞。這些單詞都是小寫字母。我們必須根據以下規則找到這組單詞的總分:
母音字母為[a, e, i, o, u 和 y]
當單詞包含偶數個母音時,單個單詞的分數為2。
否則,該單詞的分數為1。
整組單詞的得分是該組中所有單詞得分的總和。
因此,如果輸入類似於 words = ["programming", "science", "python", "website", "sky"],則輸出將為 6,因為"programming" 有 3 個母音,得分 1;"science" 有三個母音,得分 1;"python" 有兩個母音,得分 2;"website" 有三個母音,得分 1;"sky" 有一個母音,得分 1,所以 1 + 1 + 2 + 1 + 1 = 6。
為了解決這個問題,我們將遵循以下步驟:
- score := 0
- 對於 words 中的每個單詞,執行:
- num_vowels := 0
- 對於單詞中的每個字母,執行:
- 如果字母是母音,則:
- num_vowels := num_vowels + 1
- 如果字母是母音,則:
- 如果 num_vowels 是偶數,則:
- score := score + 2
- 否則:
- score := score + 1
- 返回 score
示例
讓我們看看下面的實現,以便更好地理解
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))輸入
["programming", "science", "python", "website", "sky"]
輸出
6
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP