计算来自字符串的最大连续“a”的数量。 Python 3 [英] Count the number of max consecutive "a"'s from a string. Python 3
问题描述
说使用者输入:
"daslakndlaaaaajnjndibniaaafijdnfijdnsijfnsdinifaaaaaaaaaaafnnasm"
如何找到连续的a的最大数量,如何删除a,并且只留下其中的2个而不是大的
How would you go about finding the highest number of consecutive "a" and how would you remove the "a"'s and leave only 2 of them instead of the large number of them before.
我在想将每个字母附加到一个新的空列表中,但我不确定这是否正确或后面做什么。
I was thinking of appending each letter into a new empty list but i'm not sure if that's correct or what to do after.
我真的不知道从哪里开始这个,但这是我在想:
I really don't know where to begin with this one but this is what i'm thinking:
- $ b
- 向输入添加每个字母到列表
- Ask the user for input.
- Create an empty list
- Append each letter from the input into the list
下一步我不知道。
第二次编辑
sentence = input("Enter your text: ")
new_sentance = " ".join(sentence.split())
length = len(new_sentance)
alist = []
while (length>0):
alist
print ()
推荐答案
从输入字符串开始:
input = "daslakndlaaaaajnjndibniaaafijdnfijdnsijfnsdinifaaaaaaaaaaafnnasm"
-
要获得最大连续出现次数,您可以使用:
To get the max consecutive number of occurrences, you would use:
max(len(s) for s in re.findall(r'a+', input))
-
最长不间断序列的a与2a,
您将使用: To replace only the longest unbroken sequence of "a"s with 2 "a"s, you would use:
maxMatch = max(re.finditer(r'a+', input), key= lambda m: len(m.group())) output = input[:maxMatch.start()] + "aa" + input[maxMatch.end():]
首先,我获得一个可迭代的MatchObject
测试输入字符串,然后使用max
来获取code> MatchObject
具有最大的长度。然后,我将原始字符串的部分拼接到匹配的开始,字符串aa,以及匹配结束后的原始字符串的部分,以给出最终输出。First, I obtain an iterable of
MatchObject
s by testing the input string against the regexa+
, then usemax
to obtain theMatchObject
with the greatest length. Then, I splice the portion of the original string up to the start of the match, the string "aa", and the portion of the original string after the end of the match to give you your final output.要用<2> a替换出现超过2个a的所有,您的
会使用:To replace all occurrences of more than 2 "a"s with 2 "a"s, you would use:
output = re.sub(r'a{3,}', "aa", input)
这篇关于计算来自字符串的最大连续“a”的数量。 Python 3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!