Syntax error Check if max occurring character of one string appears same no. of times in other in Python

Check if max occurring character of one string appears same no. of times in other in Python



Suppose we have two strings s and t, we have to select the most frequent character from s and then we have to check whether that particular character is present in t same number of times or not.

So, if the input is like s = "crosssection", t = "securesystem", then the output will be True, as the most frequent character in s is 's'. And there are same number of occurrences of 's' in t.

To solve this, we will follow these steps −

  • freq := a map containing all characters of s and their frequencies
  • max_freq_char = character in s where frequency is maximum
  • max_freq := frequency value of max_freq_char
  • if occurrences of max_freq_char in t is same as max_freq , then
    • return True
  • return False

Example

Let us see the following implementation to get better understanding −

 Live Demo

from collections import defaultdict
def solve(s, t) :
   freq = defaultdict(int)
   for char in s :
      freq[char] += 1
   max_freq_char = max(freq, key=freq.get)
   max_freq = freq[max_freq_char]
   if max_freq == t.count(max_freq_char) :
      return True
   return False
s = "crosssection"
t = "securesystem"
print(solve(s, t))

Input

"crosssection", "securesystem"

Output

True
Updated on: 2021-01-19T05:01:42+05:30

222 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements