0

i want to get all repeated substrings of a specific length in a string and their count. Example: string = "abcabcabcdabcd"

get_repeats(string, 3 #length of the substrings)

output:

abc (4)
bca (2)
cab (2)
BAZA
  • 59
  • 6
  • 1
    Have you tried this? Please send your code, as we only solve problems with implementations, not solve the whole question. – Ayush Garg Feb 02 '21 at 17:28

1 Answers1

4
from collections import Counter

def get_repeats(s, k):
    ctr = Counter(s[i:i+k] for i in range(len(s) - k + 1))
    return {sub: c for sub, c in ctr.items() if c > 1}

And usage:

>>> get_repeats("abcabcabcdabcd", 3)
{'abc': 4, 'bca': 2, 'cab': 2}
orlp
  • 112,504
  • 36
  • 218
  • 315