python - 计算字符串中最大连续 "a"的数量。 python 3

标签 python sorting python-3.x count

假设用户输入:

"daslakndlaaaaajnjndibniaaafijdnfijdnsijfnsdinifaaaaaaaaaaafnnasm"

您将如何找到最大数量的连续“a”以及如何删除“a”并仅保留其中的 2 个而不是之前的大量。

我正在考虑将每个字母附加到一个新的空列表中,但我不确定这是否正确或之后该做什么。

我真的不知道从哪里开始,但这就是我的想法:

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

下一步我不知道。

第二次编辑(类似的内容):

sentence = input("Enter your text: ")
new_sentance = " ".join(sentence.split())
length = len(new_sentance)
alist = []
while (length>0):
    alist
print ()

最佳答案

从输入字符串开始:

input = "daslakndlaaaaajnjndibniaaafijdnfijdnsijfnsdinifaaaaaaaaaaafnnasm"
  • 要获得最大连续出现次数,您可以使用:

    max(len(s) for s in re.findall(r'a+', input))
    
  • 只用 2 个“a”替换最长的连续“a”序列, 你会使用:

    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”和匹配结束后的原始字符串部分,以提供最终输出。

    <
  • 要用 2 个“a”替换 所有 处出现的超过 2 个“a”,您 将使用:

    output = re.sub(r'a{3,}', "aa", input)
    

关于python - 计算字符串中最大连续 "a"的数量。 python 3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18776238/

相关文章:

java - 在 JTable 中插入后如何进行排序(RowSort)?

python - 这是快速排序还是合并排序?

sorting - Haskell——使用不纯函数对列表进行排序

python-3.x - Visual Studio 代码错误 : Cannot read property 'then' of undefined

python-3.x - Python 3 virtualenv 和 Docker

python - 基于列值作为键进行拆栈和合并

python - Unicode编码错误: 'decimal' codec can't encode character u'\x00' in position 8: invalid decimal Unicode string

javascript - 当我尝试使用 tensorflow.js 模型进行预测时,出现错误 : Uncaught TypeError: Cannot read property 'length' of undefined

sql-server - 将 SSRS 报告从 Python 导出为 PDF

python - PyCharm 错误加载包列表