【问题标题】:how to find max occurrence of a letter in a string [duplicate]如何查找字符串中字母的最大出现次数[重复]
【发布时间】:2022-01-24 05:23:58
【问题描述】:

我该怎么做?

string = "ABFFFBFFFFFBF"
letter = "F"

F 的最大出现次数为 FFFFF,因此输出为:5 有人帮忙吗?

【问题讨论】:

标签: python string


【解决方案1】:

可能有一种更 Pythonic 的方式来做到这一点,但这个函数会完成这项工作:

def maxConsecutiveOccurrences(letter, string):
    count = 0
    maxCount = 0
    for ch in string:
        if ch == letter:
            count += 1
        else:
            count = 0
        if count > maxCount:
            maxCount = count
    return maxCount

maxConsecutiveOccurrences("F", "ABFFFBFFFFFBF") 返回 5

【讨论】:

    【解决方案2】:
    import re
    len(max(re.findall("F+", "ABFFFBFFFFFBF"), key=lambda x: len(x), default=[]))
    

    【讨论】:

    • lambda x: len(x) 仅相当于 len。你也可以写成max(map(len, re.findall("F+", "ABFFFBFFFFFBF")))
    【解决方案3】:
    string = "ABFFFBFFFFFBF"
    letter = "F"
    
    letter_occurence = string.count(letter)
    

    顺便说一句,您应该考虑不要将变量命名为它们的类型,变量名称应该描述变量的用途。

    【讨论】:

    • 错了。预计为 5。
    • 如果您的问题可以更具描述性,那将非常有帮助。你的意思是你想要目标字母的最大“组”?
    • 这输出 9。预期输出是 5...
    猜你喜欢
    • 2018-01-30
    • 1970-01-01
    • 2021-01-11
    • 2021-03-19
    • 1970-01-01
    • 2017-11-12
    • 2013-11-04
    • 1970-01-01
    相关资源
    最近更新 更多