Python program to find word score from list of words

PythonServer Side ProgrammingProgramming

Suppose we have few words in an array. These words are in lowercase letters. We have to find the total score of these set of words based on following rules −

  • Consider vowels are [a, e, i, o, u and y]

  • The score of an individual word is 2 when the word contains an even number of vowels.

  • Otherwise, the score of that word is 1.

  • The score for the whole set of words is the sum of scores of all words in the set.

So, if the input is like words = ["programming", "science", "python", "website", "sky"], then the output will be 6 because "programming" has 3 vowels score 1, "science" has three vowels, score 1, "python" has two vowels score 2, "website" has three vowels score 1, "sky" has one vowel score 1, so 1 + 1 + 2 + 1 + 1 = 6.

To solve this, we will follow these steps −

  • score := 0
  • for each word in words, do
    • num_vowels := 0
    • for each letter in word, do
      • if letter is a vowel, then
        • num_vowels := num_vowels + 1
    • if num_vowels is even, then
      • score := score + 2
    • otherwise,
      • score := score + 1
  • return score

Example

Let us see the following implementation to get better understanding

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))

Input

["programming", "science", "python", "website", "sky"]

Output

6
raja
Updated on 12-Oct-2021 09:08:58

Advertisements