আপনি ইনপুট স্ট্রিং-এর প্রতিটি অবস্থানের সাথে শুরু করে প্রতিটি সাব স্ট্রিংকে গণনা করতে ডিফল্টডিক্ট ব্যবহার করতে পারেন। 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'