Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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