Search code examples
pythonstringdictionarysubstringfrequency

Iterate through strings as substrings?


I have a long string from which I want to read the substrings and check how many times they have occurred.

The substring count taken from the user should be used for checking the frequency.

For example:

S = "ABCDEFGHIJKLMNOPQRSTUVABCSDLSFKJJKLOP"
substringCount = 3

def foo(S):
    pass

The function should return a dictionary that looks like this,

{'ABC':2,'DEF':1,'GHI':1,'JKL':2,'MNO':1,'PQR':1 and so on...}

The length of each key is 3 as defined earlier, which can be user-defined and any number.

How do you write such a function? What is the logic for this?


Solution

  • I'd probably do it through recursion, something along the line of

    
    s = "ABCDEFGHIJKLMNOPQRSTUVABCSDLSFKJJKLOP"
    
    userInput = int(input("Enter substring count: "))
    
    
    def get_substring_count(s, userInput, res=None):
        if res is None:
            res = {}
        if len(s) == 0 or len(s) < userInput:
            return res
        tmp_s = s[:userInput]
        if tmp_s in res:
            res[tmp_s] += 1
        else:
            res[tmp_s] = 1
        return get_substring_count(s[1:], userInput, res)