마지막부터 시작하여 가장 빈번한 요소가 3 번 이상 나타나면 빈도를 세고 중지하십시오.
from collections import Counter
a='fdwaw4helloworldvcdv1c3xcv3xcz1sda21f2sd1ahelloworldgafgfa4564534321fadghelloworld'
times=3
for n in range(1,len(a)/times+1)[::-1]:
substrings=[a[i:i+n] for i in range(len(a)-n+1)]
freqs=Counter(substrings)
if freqs.most_common(1)[0][1]>=3:
seq=freqs.most_common(1)[0][0]
break
print "sequence '%s' of length %s occurs %s or more times"%(seq,n,times)
결과 :
>>> sequence 'helloworld' of length 10 occurs 3 or more times
편집 : 당신은 당신이 작은 길이이어야 임의 입력과 일반 문자열을 취급하고있는 느낌이있는 경우, 당신은 더 나은 (당신이 필요로하는 경우 시작 속도는 작은 부분 문자열을 사용하고 적어도 세 번 나타나면 찾을 수 없을 때 중지하십시오.
from collections import Counter
a='fdwaw4helloworldvcdv1c3xcv3xcz1sda21f2sd1ahelloworldgafgfa4564534321fadghelloworld'
times=3
for n in range(1,len(a)/times+1):
substrings=[a[i:i+n] for i in range(len(a)-n+1)]
freqs=Counter(substrings)
if freqs.most_common(1)[0][1]<3:
n-=1
break
else:
seq=freqs.most_common(1)[0][0]
print "sequence '%s' of length %s occurs %s or more times"%(seq,n,times)
위와 같은 결과입니다.
이 문제에 대한 정규식 솔루션이 있는지 나는 모른다. 이것은 정규 표현식이 될 수 없지만, 파이썬은 이와 같은 일을하는 비표준 확장을 가질 수 있습니다. 일반적인 경우 이것은 동적 프로그래밍을 사용하여 해결할 수있는 LCS 문제입니다. http://en.wikipedia.org/wiki/Longest_common_subsequence_problem –