计算字符串中最大连续“a"的数量.蟒蛇 3 [英] Count the number of max consecutive "a"'s from a string. Python 3

查看:28
本文介绍了计算字符串中最大连续“a"的数量.蟒蛇 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:

  1. 询问用户输入.
  2. 创建一个空列表
  3. 将输入中的每个字母附加到列表中

接下来是什么我不知道.

What's next I have no idea.

第二次编辑(大致如此):

second edit (something along these lines):

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))
      

    • 要仅用 2 个a"替换最长的a"连续序列,你会使用:

    • 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():]
      

      首先,我通过针对正则表达式 a+ 测试输入字符串来获得 MatchObject 的可迭代对象,然后使用 max 获得 MatchObject 的最大长度.然后,我将原始字符串的一部分拼接到匹配的开头、字符串aa"和匹配结束之后的原始字符串的部分,为您提供最终输出.

      First, I obtain an iterable of MatchObjects by testing the input string against the regex a+, then use max to obtain the MatchObject 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"的数量.蟒蛇 3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆