2 min to read
Words Score - HackerRank Solution Python
Words Score is a medium level problem of python on Hackerrank that requires knowledge of string
and list
in python. In this post, you will learn how to solve Hackerrank’s Words Score problem and its solution in Python.
Problem Statement and Explanation
Function score_words takes a list of lowercase words as an argument and returns a score based on the length of each word.
The score for a single word is determined by whether it has an even or odd number of vowels.
If the word contains an even number of vowels, it receives a score of 2.
Otherwise, it receives a score of 1. The score for a list of words is simply the sum of the scores of all the words in the list.
Input Format
- The first line contains the number of words,
n
. - The next line contains
n
words.
Words Score - HackerRank Solution Python
Explanation of Solution
The first function, is_vowel()
, takes a letter as input and returns True
if the letter is a vowel, or False
otherwise. The vowels are a
, e
, i
, o
, u
.
The second function, score_words()
, takes a list of words as input and returns the total score of the words. The score of a word is calculated as follows:
- Count the number of vowels in the word.
- If the number of vowels is even, add 2 to the score.
- If the number of vowels is odd, add 1 to the score.
The third function, main()
, reads the number of words from the user, then reads the words themselves. It then calls the score_words()
function to calculate the score of the words and prints the score to the console.
For example, if the given word is code perfect plus
then the score will be:
code
=2
becauseo
ande
are vowels.perfect
=2
becausee
ande
are vowels.plus
=1
becauseu
is a vowel.
then the score will be 2 + 2 + 1 = 5
if sum of vowels in a word is even then return 2
otherwise return 1
and sum of vowels in the given word is 5
.