HackerRank Solution: The Minion Game [3 Methods]


Written By - Bashir Alam

Question: The Minion game [Python Strings]

Kevin and Stuart want to play the 'The Minion Game'.

Game Rules

Both players are given the same string, S .
Both players have to make substrings using the letters of the string S.
Stuart has to make words starting with consonants.
Kevin has to make words starting with vowels.
The game ends when both players have made all possible substrings.

Scoring

A player gets +1 point for each occurrence of the substring in the string S

For example:

String S = BANANA
Kevin's vowel beginning word = ANA
Here, ANA occurs twice in BANANA. Hence, Kevin will get 2 Points.

For better understanding, see the image below:

hackerRank

Your task is to determine the winner of the game and their score.

Function Description

Complete the minion_game in the editor below.

minion_game has the following parameters:

  • string string: the string to analyze

Prints

  • string: the winner's name and score, separated by a space on one line, or Draw if there is no winner

Input Format:

A single line of input containing the string S.
Note: The string will contain only uppercase letters: [A-Z] .

Constrains

0 < len(S) <= 10^6

Sample input:

BANANA

Sample Output:

Stuart 12

 

Possible solutions

Now we will discuss the possible solutions for the given problem. We already have been given the following function:

def minion_game(string):
    # your code goes here

if __name__ == '__main__':
    s = input()
    minion_game(s)

We have to write our code in the given function:

 

Solution-1: Using dictionary of words

Now we will use simple method to solve the given problem.

def minion_game(string: str) -> None:
    """Print the winner of the game and the score."""
    kevin = stuart = 0
    length: int = len(string)
    for i, char in enumerate(string):
        points: int = length - i
        if char in {"A", "E", "I", "O", "U"}:
            kevin += points
        else:
            stuart += points
    if kevin == stuart:
        print("Draw")
    else:
        print(*("Stuart", stuart) if stuart > kevin else ("Kevin", kevin))
if __name__ == '__main__':
    s = input()
    minion_game(s)

The game is played with a string of uppercase English letters.

The players, Stuart and Kevin, take turns to create substrings using the letters of the string. Stuart can only use consonants and Kevin can only use vowels. The player who gets the most points wins.

Points are awarded as follows: for each substring that a player creates, the player gets one point for each letter in the substring. For example, if the string is "BANANA", a player can create the substrings "BAN", "BANA", "BANAN", "BANANA", "AN", "ANA", "ANAN", "ANANA", "N", "NA", "NAN", "NANA", "A", "AN", and "ANA". The player who creates these substrings gets 13 points.

The function minion_game() takes a string as input and prints the name of the winner and their score. If the scores of Stuart and Kevin are equal, the function prints "Draw".

The function uses two variables, kevin and stuart, to keep track of the scores of the two players. It iterates over the characters in the string and for each character, calculates the number of substrings that can be formed using that character and the characters that follow it. If the character is a vowel, the points are added to Kevin's score, and if it is a consonant, they are added to Stuart's score.

Finally, the function prints the name of the winner and their score. If the scores are equal, it prints "Draw".

 

Solution-2: using if-else statements

Here is another solution for the same problem:

def minion_game(string):
    vowel = "AEIOU"
    sc = 0
    kc = 0
    x = len(string)
    for i in range(x):
        if string[i] in vowel:
            kc += x - i
        else:
            sc += x - i
    if sc > kc:
        print("Stuart", str(sc))
    elif kc > sc:
        print("Kevin", str(kc))
    else:
        print("Draw")


if __name__ == '__main__':
    s = input()
    minion_game(s)

This code is similar to the previous one, but there are a few differences.

Firstly, instead of using a for loop to iterate over the characters in the string and a range object to calculate the number of substrings that can be formed using each character, this code uses a for loop to iterate over a range object that goes from 0 to the length of the string, and uses the loop variable as an index to access the characters in the string.

Secondly, instead of using two variables, kevin and stuart, to keep track of the scores of the two players, this code uses two variables, kc and sc, to store the number of characters that Kevin and Stuart can use to form substrings.

Thirdly, instead of using the in operator to check if a character is a vowel or a consonant, this code uses the in operator to check if the character is in a string of vowels.

Finally, instead of using a ternary operator to determine the winner and print the result, this code uses an if-elif-else block to perform the same task.

 

Solution-3: Using re module

Now we will use the re module to solve the problem.

import re
def minion_game(string):
    Kevin=0
    index=0
    regex="^[AEIOU]"
    slen=len(string)
    for i in string :
        if bool(re.match(regex,i)):
            Kevin=Kevin+ (slen-index)
        index=index+1                    
    Stuart= (((slen)*(slen+1))/2)  - Kevin
    if Stuart<Kevin:
        print("Kevin " + str(int(Kevin)))
    elif Stuart >  Kevin :
        print("Stuart " + str(int(Stuart))) 
    else:
        print("Draw") 
if __name__ == '__main__':
    s = input()
    minion_game(s)

Similar to previous two solutions, this code also defines a function minion_game that takes in a string string as an argument.

It initializes two variables, Kevin and Stuart to 0. It also initializes a variable index to 0, which will be used to keep track of the current position in the string that we are checking. The function then defines a regular expression (a pattern) in the string regex that matches any uppercase vowel at the beginning of a string (^ means start of string and [AEIOU] means any of the characters A, E, I, O, or U).

It then gets the length of string and assigns it to the variable slen. The code then enters a loop that iterates through each character i in string. For each character, it checks if it matches the regular expression regex. If it does, it adds the number of remaining characters in the string (slen - index) to Kevin's score.

Regardless of whether the character matches regex, index is incremented by 1. After the loop ends, Stuart's score is calculated as the total number of substrings in string minus Kevin's score (which is calculated by multiplying the length of the string by one plus itself and dividing by 2).

Finally, the function prints out the winner of the game, with a tie being a possibility if Stuart and Kevin's scores are equal.

 

Summary

In this article, we learned three different methods to solve The minion game on Hacker Rank. Moreover, we have explained each solution deeply.

 

Further Reading

Question on Hacker Rank: The Minion game (Python Strings)

 

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