【问题标题】:logic for returning a substring with highest number of vowel返回具有最多元音的子字符串的逻辑
【发布时间】:2020-06-11 11:11:53
【问题描述】:

你得到一个字符串和一个子串的长度。你需要确定元音数量最多的子串。子串可以是元音和辅音的组合,但它应该有最多的元音。

示例:

输入 string= azerdii 子串长度=5

substrings= azerd,zerdi,erdii

erdii 的元音数量最多,所以输出应该是 erdii

请帮助我编写 Python3 中的代码

【问题讨论】:

  • 你应该分享你的尝试

标签: python-3.x string function


【解决方案1】:
#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))

【讨论】:

    【解决方案2】:
    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))
    

    【讨论】:

      猜你喜欢
      • 2017-07-09
      • 2015-02-21
      • 2013-10-26
      • 2018-02-28
      • 2021-10-22
      • 1970-01-01
      • 2021-12-25
      • 1970-01-01
      • 2018-04-08
      相关资源
      最近更新 更多