- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions

# 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 Articles
- 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 out the substrings of given strings at given positions in a set of all possible substrings in python
- Program to find sum of all elements of a tree in Python
- Program to find sum of all odd length subarrays in Python
- C# Program to find all substrings in a string
- Program to find the sum of all digits of given number 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
- Program to find all substrings whose anagrams are present in a string in Python
- Program to find maximum number of non-overlapping substrings in Python
- Program to find sum of widths of all subsequences of list of numbers in Python
- Find substrings that contain all vowels in Python