defaultdict를 사용하여 입력 문자열의 각 위치에서 시작하는 각 하위 문자열을 집계할 수 있습니다. getsubs 메소드는 호출될 때마다 더 작은 하위 문자열을 생성하는 생성기 메소드입니다.
예시
from collections import defaultdict
def getsubs(loc, s):
substr = s[loc:]
i = -1
while(substr):
yield substr
substr = s[loc:i]
i -= 1
def longestRepetitiveSubstring(r):
occ = defaultdict(int)
# tally all occurrences of all substrings
for i in range(len(r)):
for sub in getsubs(i,r):
occ[sub] += 1
# filter out all sub strings with fewer than 2 occurrences
filtered = [k for k,v in occ.items() if v >= 2]
if filtered:
maxkey = max(filtered, key=len) # Find longest string
return maxkey
else:
raise ValueError("no repetitions of any substring of '%s' with 2 or more occurrences" % (r))
longestRepetitiveSubstring("hellopeople18654randomtexthellopeoplefromallaroundthe world") 출력
이것은 출력을 줄 것입니다:
'hellopeople'