Python 计算单词总分:根据元音数量奇偶计分


发布日期 : 2019-12-18 13:14:31 UTC

访问量: 10 次浏览

从单词列表中找到单词得分的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
  • 对于每个单词,执行以下操作
  • 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