# Check if frequency of character in one string is a factor or multiple of frequency of same character in other string in Python

PythonServer Side ProgrammingProgramming

Suppose we have two strings s and t, we have to check whether the occurrences of a character in s is multiple or a factor in t.

So, if the input is like s = "xxyzzw" t = "yyyxxxxzz", then the output will be True as frequency of x in s is 2, and in t is 4, in s y is present only once, but in t there are three y's, there are same number of z in s and t and there is one w in s but not in t.

To solve this, we will follow these steps −

• s_freq := a map with all characters in s and their frequencies
• t_freq := a map with all characters in t and their frequencies
• for each ch in s_freq, do
• if ch not in t_freq, then
• go for next iteration
• if t_freq[ch] is divisible by s_freq[ch] or s_freq[ch] is divisible by t_freq[ch], then
• go for next iteration
• otherwise,
• return False
• return True

## Example

Let us see the following implementation to get better understanding −

Live Demo

from collections import defaultdict
def solve(s, t):
s_freq = defaultdict(int)
t_freq = defaultdict(int)
for i in range(0, len(s)):
s_freq[s[i]] += 1
for i in range(0, len(t)):
t_freq[t[i]] += 1
for ch in s_freq:
if ch not in t_freq:
continue
if t_freq[ch] % s_freq[ch] == 0 or s_freq[ch] % t_freq[ch] == 0:
continue
else:
return False
return True
s = "xxyzzw"
t = "yyyxxxxzz"
print(solve(s, t))

## Input

"xxyzzw", "yyyxxxxzz"

## Output

True