Python Practice › String Programs › Program 60
Frequency of every substring
Write a Python program to count every substring of a string.
Input
"abab"
Output
{'a': 2, 'ab': 2, 'aba': 1, 'abab': 1, 'b': 2, 'ba': 1, 'bab': 1}Approach
- Two nested loops pick every start and end position.
Solution
text = "abab"freq = {}for i in range(len(text)): for j in range(i + 1, len(text) + 1): sub = text[i:j] freq[sub] = freq.get(sub, 0) + 1print(freq)Output
{'a': 2, 'ab': 2, 'aba': 1, 'abab': 1, 'b': 2, 'ba': 1, 'bab': 1}Line by line
Lines 3-5
text[i:j] visits every substring once: “a”, “ab”, “aba”, “abab”, “b”, …
Learn the concept
New to this topic? Read the lesson, then come back.