给定一个字符串 s,在列表 ["a"、"e"、"i"、"o"、[=14= 中找到包含最大元音个数的 k 个元素的子串]]

Given a string s, find the substring with k elements that contains the maximum number of vowels among the list ["a", "e", "i", "o", "u"]

给定一个字符串 s,我想在列表 ["a", "e", "i", "o", "u"] 中找到长度为 k 且包含最大元音字母的子串 用户开始输入字符串 s 及其长度 k。 例如,如果 s = "sfjfio" 和 k = 3 那么输出应该是字符串 "fio" 如果我有多个满足此条件的子字符串,则输出应该是从最低索引开始的子字符串。 如果没有子串满足要求那么我希望输出只是原来的字符串 s 回来。我从这段代码开始,但有点困惑和卡住了。它似乎有效,但当我尝试几个例子时并不总是给出正确的答案。 我几天前才开始使用 python,还不是很了解。任何帮助都会非常棒!

s = input("please enter s ")
k = input("please enter k ")

from itertools import combinations

allsubstrings = [s[a:b] for a, b in combinations(range(len(s) + 1), r = 2)]
#if I am right this should give me all the possible substrings in s

#I will only take the ones of length k and put them in an array
substring = []
for i in allsubstrings:
    if len(i) == k:
        substring.append(i)

vowels = ["a", "e", "i", "o", "u"]
vowcount = []
#here I create an empty array to store the number of vowels in each substring

#now I will loop over each substring and check if it contains a vowel 
#I need to check if it contains each one of my vowels though I am not really sure if my code does that or just checks for one of the vowels
for j in substring:
    count = 0
    for i in vowels:
        if i in j:
            count = count + 1
        vowcount.append(count)

#now I check the maximum number of vowels in a given substring
#since I am looping through the substrings in order their vowel count also gets stored in order in my vowcount array thus I can take the index of the max(vowcount) as the index of the substring j that satisfies the condition
if vowcount:
    if max(vowcount) != 0:
        print(substring[vowcount.index(int(max(vowcount)))])
else:
   print(s)

为此您不需要 itertools,您可以遍历所有可能的子字符串,这些子字符串从位置 0len(s)-k 开始,长度为 k 个字符。您也不需要存储每个子字符串的元音计数,只要元音计数高于先前的最大值就保存子字符串。您应该将您的代码合并到一个函数中,以便更轻松地调用不同的输入组合。例如:

def max_vowels(s, k):
    vowels = ['a', 'e', 'i', 'o', 'u']
    # initialise our state variables
    vmax = -1     # maximum number of vowels seen in a subatring
    smax = ''     # the substring in which we found the maximum
    # iterate over all the possible substrings, which start from positions 0 to len(s)-k
    for i in range(len(s)-k+1):
        # extract the substring
        substr = s[i:i+k]
        # count the number of vowels
        num_vowels = sum(1 if c in vowels else 0 for c in substr)
        # is it a new maximum count? if so, update our state
        if (num_vowels > vmax):
            vmax = num_vowels
            smax = substr
    # all substrings visited, return the one with the most vowels
    return smax
        
print(max_vowels('sfjfio', 3))
print(max_vowels('ioosdfghjkaeibnffbjfbnfoii', 4))

输出:

fio
ioos

这是一种利用 collections.<b>Counter</b> 的替代方法,如果您不允许使用库方法,只需在下面的 num_vowels_in_str 中添加您自己的计算一个字符串中元音数量的逻辑:

from collections import Counter

def num_vowels_in_str(s):
    ch_counts = Counter(s.lower())
    return sum(ch_counts[ch] for ch in "aeiou")

s = input("Please enter s: ")
k = int(input("Please enter k: "))

k_length_substrs = [
    s[i:j]
    for i in range(len(s))
    for j in range(i + 1, len(s) + 1)
    if j - i == k
]

num_vowels_per_substr = [
    num_vowels_in_str(substring)
    for substring in k_length_substrs
]

max_vowels = max(num_vowels_per_substr)

result_index = next(
    i 
    for i, num_vowels in enumerate(num_vowels_per_substr)
    if num_vowels == max_vowels
)

result = k_length_substrs[result_index]
print(result)

用法示例:

Please enter s: sfjfio
Please enter k: 3
fio