আপনি 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)
# সব সাবস্ট্রিং-এর অকুরেন্স ট্যালি
for i in range(len(r)):
for sub in getsubs(i, r):
occ[sub] += 1
# ২টির কম অকুরেন্স वाले সাবস্ট্রিং ফিল্টার আউট
filtered = [k for k, v in occ.items() if v >= 2]
if filtered:
maxkey = max(filtered, key=len) # সবচেয়ে লম্বা স্ট্রিং খুঁজুন
return maxkey
else:
raise ValueError("no repetitions of any substring of '%s' with 2 or more occurrences" % (r))
longestRepetitiveSubstring("hellopeople18654randomtexthellopeoplefromallaroundthe world")
আউটপুট
এটি আউটপুট দেবে:
'hellopeople'