- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

# Program to find sum of beauty of all substrings in Python

Suppose we have a string s. We have to find the sum of beauty of all of its substrings. The beauty of a string is actually the difference in frequencies between the most frequent and least frequent characters. So if the string is "abaacc", then its frequency is 3 - 1 = 2.

So, if the input is like s = "xxyzy", then the output will be 5 because the substrings with non-zero beauty are ["xxy","xxyz","xxyzy","xyzy","yzy"], each has beauty value 1.

To solve this, we will follow these steps −

res:= 0

for i in range 0 to size of s - 1, do

for j in range i+2 to size of s - 1, do

c:= a map containing characters frequency of substring of s from index i to j

v:= list of all frequency values of c

res := res +(maximum of v - minimum of v)

return res

## Example

Let us see the following implementation to get better understanding −

from collections import Counter def solve(s): res=0 for i in range(len(s)): for j in range(i+2,len(s)): c=Counter(s[i:j+1]) v=c.values() res+=(max(v)-min(v)) return res s = "xxyzy" print(solve(s))

## Input

"xxyzy"

## Output

5

- Related Questions & Answers
- C++ Program to find minimal sum of all MEX of substrings
- Program to find total sum of all substrings of a number given as string in Python
- Program to find sum of the sum of all contiguous sublists in Python
- Program to find sum of all elements of a tree in Python
- Program to find out the substrings of given strings at given positions in a set of all possible substrings in python
- Program to find sum of all odd length subarrays in Python
- Program to find the sum of all digits of given number in Python
- Program to find sum of widths of all subsequences of list of numbers in Python
- Python program to find the sum of all items in a dictionary
- Python Program to Find the Sum of all Nodes in a Tree
- Program to find XOR sum of all pairs bitwise AND in Python
- C# Program to find all substrings in a string
- Program to find maximum number of non-overlapping substrings in Python
- Program to find out the number of pairs of equal substrings in Python
- Program to find sum of the 2 power sum of all subarray sums of a given array in Python