计算连续三次重复的数量

3 投票
3 回答
57 浏览
提问于 2025-04-14 15:36

我该如何在Python中实现一个函数,用来计算连续出现三次的情况呢?

举个例子:给定字符串'111111aaaa',这个函数需要返回3,因为在这个字符串中,有三组连续的三次重复(可以看作是111-111-aaa-a)。

def count_repeat(str: str) -> int:
    repeat = 0
    for i in range(len(str) - 2):
        if str[i] == str[i + 1] == str[i + 2]:
                repeat += 1
    return repeat

3 个回答

1

这里有另一种使用 while 循环的解决方案

def count_repeat(s: str):
    repeat: int = 0
    i : int = 0
    while i < len(s)-2:
        if s[i] == s[i+1] == s[i+2]:
            repeat += 1
            i += 3
        else:
            i += 1
    return repeat

几点说明:

  1. 我把参数名从 str 改成了 s。因为使用已经被占用的内置名称作为参数或变量名可能会引发问题。
  2. 由于这个方法是向前看两个空格,所以我们可以在字符串结束前的两个位置就退出循环。
  3. 每当我们发现有重复的情况时,可以直接跳过重复后的下一个位置。
1

另一种解决方案,使用 re 模块:

import re

s = "111111aaaa"

num_repetitions = sum(1 for _ in re.finditer(r"(.)\1{2}", s))
print(num_repetitions)

输出结果:

3
2

这里有一个可以满足你需求的函数:

def count_repeat(s: str) -> int: 
    num = 0
    cur_rep = 1
    for i in range(1, len(s)): 
        if s[i] != s[i - 1]: # When the repetitions stops, add to answer and clear cur_rep
            num += cur_rep // 3
            cur_rep = 1
        else: # Length of current repetition plus one
            cur_rep += 1

    num += cur_rep // 3 # Remember to add last part

    return num

这个函数会遍历字符串,并根据以下两种情况进行处理:

  1. 如果当前字符和前一个字符相同,就把 cur_rep 加一。
  2. 如果当前字符和前一个字符不同,就更新结果,并清空 cur_rep

cur_rep 表示当前相同字符的长度。

补充说明:

  1. 我把你之前的变量名 str 改成了 s。因为 str 在 Python 中是一个数据类型的名称,可能会引发一些潜在的问题。
  2. 你可以把 3 改成其他数字,以计算不同长度的重复字符。(感谢 anatolyg 的评论)

撰写回答