Find all substring frequencies in a string

In this program, we will take a string as input and find all substring frequencies in a string.

Steps to solve the program
  1. Take a string as input and create an empty list.
  2. Using for loop with range() function find all the possible substring combinations from the given string and add them to the empty list.
  3. Create an empty dictionary.
  4. Use for loop to iterate over each combination of the substring from the list.
  5. Add the combination as the key and its occurrences in the list as its value in the dictionary.
  6. Print the output.
				
					#Input string
str1 = "abab"
test = []

for i in range(len(str1)):
    for j in range(i+1,len(str1)+1):
        test.append(str1[i:j])

dict1 = dict()
for val in test:
    dict1[val] = test.count(val)

#Printing output
print(dict1)
				
			

Output :

				
					{'a': 2, 'ab': 2, 'aba': 1, 'abab': 1, 'b': 2, 'ba': 1, 'bab': 1}
				
			

check if the substring is present in the string or not

print the index of the character in a string.

Leave a Comment