This Python script is designed to find the substring of a given length that contains the maximum number of vowels in a given string. The user inputs a string and the length of the substring to be found. The script then iterates through the string, keeping track of the number of vowels in the current and best substrings. If it finds a substring with more vowels than the current best, it updates the best substring.
CodeRankGPT is a tool powered by GPT-4 that quietly assists you during your coding interview, providing the solutions you need.
In real-time and absolutely undetectable 🥷
The solution works by initializing two variables, 'cur' and 'best', to the sum of vowels in the first 'k' characters of the string. It then iterates over the rest of the string, adding 1 to 'cur' if the current character is a vowel and subtracting 1 if the character 'k' positions back is a vowel. If 'cur' is greater than 'best', it updates 'best' and stores the current position. If 'best' is greater than 0 after the loop, it returns the substring starting at the stored position and of length 'k'. Otherwise, it returns 'Not found!'.
import math
import os
import random
import re
import sys
def findSubstring(s, k):
vowels = ["a", "e", "i", "o", "u"]
cur = best = sum([c in vowels for c in s[:k]])
ans = 0
for i in range(k, len(s)):
cur += s[i] in vowels
cur -= s[i - k] in vowels
if cur > best:
best = cur
ans = i - k + 1
if best > 0:
return s[ans:(ans+k)]
else:
return "Not found!"
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
s = input()
k = int(input().strip())
result = findSubstring(s, k)
fptr.write(result + '
')
fptr.close()
If you have a HackerRank Certification test or a coding interview coming up, you can use CodeRankGPT to your advantage. It will assist you during your test and help ensure you get the certification or the job.
AI is here now, and other candidates might be using it to get ahead and win the job. 🧐
The form has been successfully submitted.