Python 程序从单词列表中查找单词得分

pythonserver side programmingprogramming更新于 2025/12/23 15:08:17

假设数组中有几个单词。这些单词都是小写字母。我们必须根据以下规则找到这些单词集的总分数 −

  • 考虑元音为 [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
    • 对于 word 中的每个字母,执行
      • 如果字母是元音,则
        • num_vowels := num_vowels + 1
    • 如果 num_vowels 为偶数,则
      • score := score + 2
    • 否则,
      • score := score + 1
  • return 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

相关文章


有用资源