当给定字符串中出现的N个已知数目时,查找字符串中重复的项

2024-09-30 08:20:03 发布

您现在位置:Python中文网/ 问答频道 /正文

有没有办法做到以下几点,而不使用暴力之类的?你知道吗

str = "abbcccddddefefef"
N = 3
repeated_term = func(str,N)

print(repeated_term )
> ['c','ef']


N = 2
term = func(str,N)

print(term)   
> ['b', 'dd', 'fe']    # Thanks to @blhsing for the correction!

等等。。。你知道吗


Tags: thetoforrepeatedddfuncprintterm
1条回答
网友
1楼 · 发布于 2024-09-30 08:20:03

您可以安装PyPi regex module,它支持可变宽度的lookback模式,以使用正则表达式来查找重复N-1次的序列:

import regex
def func(s, N):
    return regex.findall(r'(?=(.+?)(?:\1){%d}(?!\1))(?<!\1)' % (N - 1), s)

以便:

func("abbcccddddefefef", 3)

退货:

['c', 'ef']

而且:

func("abbcccddddefefef", 2)

退货:

['b', 'dd', 'fe']

注意,N=2的预期输出是不正确的,因为'dd''fe'也正好出现了2次。你知道吗

相关问题 更多 >

    热门问题