logic for returning a substring with highest number of vowel - python-3.x

You are given with a string and length of a substring .You are required to determine the substring with highest number of vowels .The substring can be a combination of vowel and consonant but it should have the highest number of vowels.
example:
input
string= azerdii
length of substring=5
substrings= azerd,zerdi,erdii
erdii has highest number of vowels so output should be erdii
Kindly help me with the code in Python3

#fetch all substrings
string_is = 'azerdii'
sub = 5
length = len(string_is)
sub_ar = [string_is[i:j+1] for i in range(length) for j in range(i,length)]
#print(sub_ar)
#fetch substrings of a length = 5
sub_ar_is = []
for each in sub_ar:
if len(each) == 5:
sub_ar_is.append(each)
print(sub_ar_is)
data_dict = {}
data = ['a','e','i','o','u']
for each in sub_ar_is:
count = 0
for each_is in data:
count = count + each.count(each_is)
data_dict.update({each:count})
print(data_dict)
print("Substring is: ", max(data_dict, key=data_dict.get))

def findSubstring(s, k):
vowels = "aeiou"
return_output = ["Not found!"]
max_countt = 0
# loop size such that index don't gets out of range
length = len(s)-k+1
for i in range(length):
# temporary storage of vowel count
sum_count = 0
# getting string of desire size
output = s[i:i+k]
# count of vowels in the string
for vowel in vowels:
sum_count += output.count(vowel)
# if vowels in the string is greater than string having max vowels
# replace the max vowel string and number of max vowel count
if max_countt < sum_count:
return_output = output
max_countt = sum_count
# return output
return "".join(return_output)
print(findSubstring("azerdii", 5))

Related

Why doesn't this function always return the longest palindromic substring in a string?

I wrote this solution to a codewars problem (https://www.codewars.com/kata/longest-palindrome). It passes all but one of the tests, in which it returns 2 instead of 7.
Why might this solution fail?
def longest_palindrome (s):
if s == '':
return 0
if len(s) == 1:
return 1
palindrome_lengths = []
for i in range(len(s)):
# determine all indices for the character
indices = []
for p, character in enumerate(s):
if character == s[i]:
indices.append(p)
# check if each substring is a palindrome and, if so, add length to palindrome_lengths
index = 1
while index < len(indices):
# grab the substring
substring = s[indices[0]:indices[index]+1]
# reverse the substring
reverse_substring = substring[::-1]
# if forward substring equals reverse, add length to a list of lengths
if substring == reverse_substring:
palindrome_lengths.append(len(substring))
index += 1
if palindrome_lengths == []:
return 1
else:
palindrome_lengths.sort(reverse=True)
return palindrome_lengths[0]
You never check any substring that doesn't start with the first occurrence of its first letter in the original string (for example, for the string "mamadam", you never test the substring starting with the second m).

Fill Alphabets - Word by Word using python

The program must accept a string S containing multiple words as the input.The program must form a new string W based on the following conditions. - The number of words in S and W must be equal. - The length of each word in S and W must be equal. - The alphabets in W must be filled word by word from the alphabets in S. Finally, the program must print the string W as the output.
Boundary Condition(s): 0 <= Length of S <= 1000 1 <= Length of each word in S <= 20
Here is a not optimized version. There probably is a shorter version with map or lambda but ...
def shuffle(S):
words = S.split(' ')
letters = sorted([c for c in S if c != ' '])
new_words = []
i = 0
for l in letters:
placed = False
while not placed:
if len(new_words) < len(words):
new_words.append(l)
placed = True
else:
if len(new_words[i]) < len(words[i]):
new_words[i] += l
placed = True
i += 1
if i == len(words):
i = 0
return ' '.join(new_words)

Longest sub string and its length without repeated chars

def findLongestSubstring(string):
st = 0 # starting point of current substring.
maxlen = 0 # maximum length substring without repeating characters.
start = 0 # starting index of maximum length substring.
pos = {} # Hash Map to store last occurrence of each already visited character
pos[string[0]] = 0 #Last occurrence of first character is index 0
for i in range(1, len(string)):
# If this character is not present in hash, character, store this in hash.
if string[i] not in pos:
pos[string[i]] = i
else:
# If this character is present in hash then check if that occurrence
# is before or after starting point of current substring.
if pos[string[i]] >= st:
# find length of current substring and update maxlen and start accordingly.
currlen = i - st
if maxlen < currlen:
maxlen = currlen
start = st
# Next substring will start after the last occurrence of current
# character to avoid its repetition.
st = pos[string[i]] + 1
pos[string[i]] = i # Update last occurrence of current character.
# Compare length of last substring with maxlen & update maxlen and start accordingly.
if maxlen < i - st:
maxlen = i - st
start = st
# The required longest substring without repeating characters is from string[start]
#to string[start+maxlen-1].
print("Lenth is:", len(string[start : start + maxlen]) )
print( string[start : start + maxlen] )
return string[start : start + maxlen]
Above code works for the most part. But for below test case, it fail. What am I doing wrong? Code was copied from GeeksforGeeks. Code is returning "ba", instead of "bad".
assert(findLongestSubstring("babad") == "bad" )
Your last length check should work if you increment i by 1.
# Compare length of last substring with maxlen & update maxlen and start accordingly.
if maxlen < (i + 1) - st:
maxlen = (i + 1) - st
start = st

replace an occurrence with a distinct number every loop

The first occurrence of the character in the string will be replaced with a 1, the second occurrence with a 2, etc.
ive tried using for loop and the max function to replace the last occurence but it doesnt seem to work.
string=str(input('string: '))
x=input('character: ')
list=[]
for i in range(len(string)):
if string[i]==x:
list.append(i)
Z=str(max(list))
print(string.replace(x,Z,[::-1]))
the output should be as following
string: departmentofcomputerscience
character: e
d1partm2ntofcomput3rsci4nc5
Here's a way to do it.
Use a counter for each character in the loop, and store values in the list, then merge the list. Use the current value if not equal to the character, counter otherwise:
string=str(input('string: '))
x=input('character: ')
# Use list to store results and a counter
l = []
counter = 0
for c in string:
if c==x:
counter += 1
l.append(str(counter))
else:
l.append(c)
# Merge the resulting list into string
res = "".join(l)
# Output the result
print(res)
For the input string: departmentofcomputerscience
and the character: e
The output is
d1partm2ntofcomput3rsci4nc5
Here is another way to achieve the goal using a list and the method replace():
string = str(input('string: '))
x = input('character: ')
list = []
for i in range(len(string)):
if string[i] == x:
list.append(i) # add all indexes to replace to the list
if len(list) > 0:
j = 0
for i in range(len(list)):
j += 1
string = string.replace(string[list[i]], str(j), 1) # replace the element once at time
print(string)
For string: departmentofcomputerscience
character: e
Output: d1partm2ntofcomput3rsci4nc5
def replace(s, c):
'''
#parameter s: input string
#parameter c: input character to be replaced
#return s: where every occurence of c is
replaced by it's nth occurence
'''
so = list(s)
j = 1
for i in range(len(so)):
if so[i] == c:
so[i] = str(j)
j = j + 1
return ''.join(so)

Python3 String Manipulation Using Replacement

I want to create a list of vowels from a string that contains letters and still have the consonants in that string. I have something that worked for a particular string, with one occurrence in that string but when I have multiple occurrences, it does not work.
PRINCELY worked well,
EMEKA did not work.
I need help!
alphabets = {"A":1,"B":2,"C":3, "D":4,"E":5,"F":6,"G":7,"H":8,"I":9,"J":1,"K":2,"L":3,"M":4,"N":5,"O":6,"P":7,"Q":8,"R":9,"S":1,
"T":2,"U":3,"V":4,"W":5, "X":6,"Y":7,"Z":8}
def digit_sum(num):
return sum( [ int(char) for char in str(num) ] )
def numerology(word):
total = 0
for letter in word:
total += alphabets[letter]
total = digit_sum(total)
return total
fan = 'PRINCELY'
def vowels(fan):
vowels=[]
if 'I' in fan:
vowels.append(9)
fan1=fan[:fan.index('I')]+fan[fan.index('I')+1:]
consonant = fan1
if 'E' in fan:
vowels.append(5)
fan2=fan1[:fan1.index('E')]+fan1[fan1.index('E')+1:]
consonant = fan2
if 'A' in fan:
vowels.append(1)
fan3=fan2[:fan2.index('A')]+fan2[fan2.index('A')+1:]
consonant = fan3
if 'O' in fan:
vowels.append(6)
fan4=fan3[:fan3.index('O')]+fan3[fan3.index('O')+1:]
consonant = fan4
if 'U' in fan:
vowels.append(3)
fan5=fan4[:fan4.index('U')]+fan4[fan4.index('U')+1:]
consonant = fan5
print(vowels)
print(consonant)
print(digit_sum(sum(vowels)))
cons = numerology(consonant)
print(cons)
vowels(fan)
#outputs
#[9, 5]
#PRNCLY
#5
#7
The easiest way is to use str.translate with an appropriate translation table. First we'll make a function that takes a character and returns the appropriate number as a string. We'll use that to build a translation table. Then we just use that translation table on the string
def get_number(char):
return str(ord(char.lower())-96) # lowercase ascii letters start at 97
vowels = (vowel for letter in 'aeiou' for vowel in (letter, letter.upper()))
table = str.maketrans({vowel: get_number(vowel) for vowel in vowels})
print('PRINCELYPRINCELY'.translate(table))
# PR9NC5LYPR9NC5LY
To sort the string into vowels and consonants, and then turn the vowels into numbers you could do
s = 'PRINCELYPRINCELY'
vowels = [ord(char.lower())-96 for char in s if char.lower() in 'aeiou']
# [9, 5, 9, 5]
consonants = s.translate(str.maketrans('','','aeiouAEIOU'))
# 'PRNCLYPRNCLY'

Resources