我有一串小写英文字母和一个整数子串长度。我必须找到包含最多元音的长度的子字符串。
示例:
s = '阿泽尔迪'
k = 5
可能的 5 个字符子字符串是:
- 'azerd' 元音数量 = 2
- 'zerdi' 元音数量 = 2
- 'erdii' 元音数量 = 3
所以答案应该是“erdii”
这是我的代码:
def findSubstring(s, k):
i = 0
lst = []
count = 0
tempL = []
while(i != len(s)):
a = i+k
temp = s[i:a]
lst.append(temp)
if a != len(s):
i+=1
else:
break
for word in lst:
for alphabet in word:
if alphabet in 'aeiou':
count += 1
tempL.append(count)
print(lst)
print(tempL)
return
s = input()
k = int(input().strip())
print(findSubstring(s, k))
I'm getting
['azerd', 'zerdi', 'erdii']
[2, 4, 7]
但是计数应该是
[2, 2, 3]
请原谅我可能犯的任何愚蠢错误。我一定会感谢任何帮助。
最佳答案
您需要在第 17 行重置 count=0
。
试试这个代码
def findSubstring(s, k):
i = 0
lst = []
count = 0
tempL = []
while(i != len(s)):
a = i+k
temp = s[i:a]
lst.append(temp)
if a != len(s):
i+=1
else:
break
for word in lst:
count = 0
for alphabet in word:
if alphabet in 'aeiou':
count += 1
tempL.append(count)
print(lst)
print(tempL)
return
s = 'azerdii'
k = 5
print(findSubstring(s, k))
关于python - 从字符串中查找元音子串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69849157/