HackerRank Solution: Words Score in Python [3 Methods]


Hacker Rank Python

Author: Bashir Alam
Reviewer: Deepak Prasad

Question: Words Score - Hacker Rank (Python Debugging)

In this challenge, the task is to debug the existing code to successfully execute all provided test files.
Consider that vowels in the alphabet are a, e, i, o, u, and y.
Function score_words takes a list of lowercase words as an argument and returns a score as follows:
The score of a single word is 2 if the word contains an even number of vowels. Otherwise, the score of this word is 1. The score for the whole list of words is the sum of the scores of all words in the list.
Debug the given function score_words such that it returns a correct score.
Your function will be tested on several cases by the locked template code.

Input format:

The input is read by the provided locked code template. In the first line, there is a single integer n denoting the number of words. In the second line, there are n space-separated lowercase words.

Constraints:

  • 1 <= n <= 20
  • Each word has at most  20 letters and all letters are English lowercase letters

Output Format:

The output is produced by the provided and locked code template. It calls function score_words with the list of words read from the input as the argument and prints the returned score to the output.

Sample Input 0:

2
hacker book

Sample Output 0:

4

Explanation 0:

There are two words in the input: hacker and book. The score of the word hacker is 2 because it contains an even number of vowels, i.e. 2 vowels, and the score of the book is 2 for the same reason. Thus the total score is 2+2 = 4.

Sample Input 1:

3
programming is awesome

Sample Output 1:

4

Explanation 1:

There are 3 words in the input: programming, is, and awesome. The score of programming is 1 since it contains 3 vowels, an odd number of vowels. The score of is also 1 because it has an odd number of vowels. The score of awesome is 2 since it contains 4 vowels, an even number of vowels. Thus, the total score is 1+1+2 = 4.

 

Possible solutions

Now let us move toward the solutions. In this article, we will solve the question using various solutions. We will be using the following solutions to solve the give hackerrank question.

  1. Creating a function to return list of vowels
  2. Using regular expressions
  3. Using filter() method

Let us now explain each of the above methods in detail.

 

Solution-1: Create a function to return a list of vowels

We will create two functions: The first function will return a list of vowels and the second function will count the words as shown below:

# creating a function that returns vowels
def is_vowel(letter):
    return letter in ['a', 'e', 'i', 'o', 'u', 'y']

# Main function that counts the words
def score_words(words):
    score = 0
    for word in words:
        num_vowels = 0
        for letter in word:
            if is_vowel(letter):
                num_vowels += 1
        if num_vowels % 2 == 0:
            score += 2
        else:
        # Words Score in Python 
            score += 1
        # Words Score in Python 
    return score

# taking the input from user
n = int(input())
words = input().split()
print(score_words(words))

The is_vowel function takes a letter as an input and returns True if the letter is a vowel (i.e., 'a', 'e', 'i', 'o', 'u', or 'y'), and False otherwise.

The score_words function takes a list of words as input and returns a score based on the following rules:

  • For each word, the function counts the number of vowels in the word. If the number of vowels is even, the score for the word is 2. If the number of vowels is odd, the score for the word is 1.
  • The final score is the sum of the scores for all the words.

The score_words function first initializes a variable score to 0. It then iterates over the list of words, and for each word it counts the number of vowels using the is_vowel function. If the number of vowels is even, it adds 2 to the score, and if the number of vowels is odd, it adds 1 to the score. Finally, it returns the total score.

The main function begins by reading an integer n from the input, which represents the number of words. It then reads a space-separated list of n words from the input and splits it into a list of words. It then calls the score_words function on this list and prints the result.

 

Solution-2: Using regular expressions

Now we will use the regular expressions in the main functions. We can import the re module in the beginning and use the regular expressions.

# importing the re module
import re

# creating a function to count the words
def score_words(A):
    score=0
    for i in A:
        if len(re.findall(r"[aeiouy]",i)) %2 == 0: score += 2 
        else: score+=1 
    return score

    # using __name__= __main__ to call the function
if __name__ == '__main__':
    N = int(input())
    print(score_words(input().split()))

This is a complete program that calculates the score of a list of words using the score_words function defined earlier.

The program starts by importing the re (regular expression) module, which is used in the score_words function.

Then, it defines the score_words function as before.

The if __name__ == '__main__': block is a common idiom in Python to specify the main entry point of the program. It will only be executed if the script is run directly (e.g., python script.py), but not if it is imported as a module in another script.

Inside the if block, the program reads an integer N from the input and then reads a space-separated list of N words from the input. It then calls the score_words function on this list and prints the result.

 

Solution-3: Using filter() function

Python's filter() is a built-in function that allows you to process an iterable and extract those items that satisfy a given condition. This process is commonly known as a filtering operation. Let us use the filter() method to solve the given problem:

# creating function
def score_words(words:list) -> int:
    
    # create internal list of vowels
    VOWELS = ['a', 'e', 'i', 'o', 'u', 'y']
    
    # initialize score
    score = len(words)
    
    for w in words:
        # filter the vowels in the word
        vowels_in_w = list(filter(lambda x: x in VOWELS, w)) 
        
        # add +1 score for words with even nr. of vowels
        if len(vowels_in_w) % 2 == 0:
            score += 1 
    
    return score

    
# read inputs
n = int(input())
words= input().split()

# compute and print score
score = score_words(words)
print(score)

This version of the score_words function calculates the score of a list of words using the following rules:

  • Each word in the list adds 1 to the score.
  • If a word has an even number of vowels, it adds 1 to the score.

The function starts by defining a list of vowels, VOWELS, and initializing the score variable to the number of words in the list. It then iterates over the words in the list and filters the vowels in each word using a lambda function and the filter function. It then checks the length of the list of vowels in the word to see if it is even or odd, and if it is even, it adds 1 to the score. Finally, the function returns the total score.

The main program reads an integer n from the input, which represents the number of words, and then reads a space-separated list of n words from the input. It then calls the score_words function on this list and prints the result.

 

Summary

In this short article, we learned how we can solve the word count problem on HackerRank using various methods.

 

Further Readings

Question on Hacker Rank: Word Score

 

Bashir Alam

Bashir Alam

He is a Computer Science graduate from the University of Central Asia, currently employed as a full-time Machine Learning Engineer at uExel. His expertise lies in Python, Java, Machine Learning, OCR, text extraction, data preprocessing, and predictive models. You can connect with him on his LinkedIn profile.

Can't find what you're searching for? Let us assist you.

Enter your query below, and we'll provide instant results tailored to your needs.

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can send mail to admin@golinuxcloud.com

Thank You for your support!!

Leave a Comment