Jun-28-2020, 07:37 PM
(This post was last modified: Jun-28-2020, 07:41 PM by Emekadavid.)
(Jun-27-2020, 11:13 PM)deanhystad Wrote: In your program a letter is either a vowel or it isn't (no confusion about Y) you certainly don't have to test twice.Thanks for your reply about using an equation. I never ever thought of that. It escaped my notice. I want to say a big thank you. It really helped. Now, it is optimized and the problem solved. Here is my code. I used a generator because the string length being long I didn't want something on memory. You all really helped me on this one. Now I have learned something new about python thanks to all of you.
Why are you making a substring? You know how long the string is. You know the index of the letter you are testing. Can't you come up with an equation to calculate the number of substrings? Why do you insist on counting when math is much faster?
If you have a string of length N, how many different substrings can you make that start with string[i]? Present answer in the form of an equation. Instead of solving a simple equation you would rather count from 0 to 9,999 in a loop and then do it again from 1 to 9,999, 1 to 9,999. Now you want to make a substring that is 10,000 characters long, then 9,999 characters long, then 9,998, etc...
No wonder your program is slow.
def getNextChar(text): n = 0 while n < len(text) : yield (text[n], n) n += 1 def count_cons(text, vowels): countVowels = 0 countConsonants = 0 nextChar = getNextChar(text) for char in nextChar: if char[0] not in vowels : countConsonants += len(text) - char[1] else : countVowels += len(text) - char[1] if countConsonants > countVowels : print('Stuart', countConsonants) elif countVowels > countConsonants : print('Kevin', countVowels) else : print('Draw') def minion_game(string): # your code goes here assert 0<len(string)<=1000000 vowels = 'AEIOU' count_cons(string, vowels) if __name__ == '__main__': s = input() minion_game(s)
(Jun-28-2020, 07:20 PM)GOTO10 Wrote:Thanks. I used an equation and it did the job. I appreciate your kindness.(Jun-27-2020, 11:13 PM)deanhystad Wrote: No wonder your program is slow.
I had to use significantly larger strings than the testcase.txt file to finally see a consistent difference in execution speed, but doing that did show that your code has room for improvement. As deanhystad has indicated, the inefficiencies in your code stem from doing an unnecessary second test when distinguishing consonants from vowels, and from your method of counting substrings. Instead of usinglen(text[i:])
as you currently do, you should be able to get this same value from an equation that uses variables you have already defined at this point in your code.