This is a hackerrank question and I am kind of a noob here. 5/15 testcases are working but when the string to analyze is too big, the testcase is being terminated due to timeout. Any guidance will be much appreciated.
The question - Both players are given the same string, . Both players have to make substrings using the letters of the string . Stuart has to make words starting with consonants. Kevin has to make words starting with vowels. If a substring appears x times, it will constitute +x score. The game ends when both players have made all possible substrings.
def minion_game(string):
vowels = {'A', 'E', 'I', 'O', 'U'}
strlen = len(string)
Stuart, Kevin = 0, 0
words = set([])
for i in range(strlen):
for j in range(i, strlen):
temp_word = string[i:j + 1]
temp_word_length = j-i+1
if temp_word not in words:
words.add(temp_word)
no_of_search = strlen - temp_word_length + 1
score = sum(temp_word == string[x : x + temp_word_length] for x in range(no_of_search))
if string[i] in vowels:
Kevin += score
else:
Stuart += score
if Stuart > Kevin:
print('Stuart', Stuart)
elif Kevin > Stuart:
print('Kevin', Kevin)
else:
print('Draw')
I just looked at the question source.
This is probably the shortest way you could do it.
def minion_game(string):
vowels = ['A', 'E', 'I', 'O', 'U']
kevin = 0
stuart = 0
for i in range(len(string)):
if s[i] in vowels:
kevin += len(s)-i
else:
stuart += len(s)-i
if stuart > kevin:
print('Stuart '+ str(stuart))
elif kevin > stuart:
print('Kevin ' + str(kevin))
else:
print('Draw')
s = input()
minion_game(s)
This part iterates through each letter in the input string and checks whether it is a vowel.
for i in range(len(string)):
if s[i] in vowels:
HackerRank automatically gives you the below, if you actually check so that's where it is declared.
s = input()
minion_game(s)