Python Practice › String Programs › Program 60

Frequency of every substring

MediumString Programs · 60 of 106

Write a Python program to count every substring of a string.

Advertisement
Input
"abab"
Output
{'a': 2, 'ab': 2, 'aba': 1, 'abab': 1, 'b': 2, 'ba': 1, 'bab': 1}

Approach

  1. Two nested loops pick every start and end position.

Solution

Python
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.

More string programs

← All 106 String Programs

Leave a Comment