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