Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,999 questions

51,944 answers

573 users

How to count the characters need to be removed so that two strings become anagram in Python

3 Answers

0 votes
def CountCharactersNeedToBeRemovedForAnagram(str1,  str2) :
    TotalABCLetters = 26
    count1 = [0] * (TotalABCLetters)
    count2 = [0] * (TotalABCLetters)
    size1 = len(str1)
    size2 = len(str2)
        
    # count char frequency str1
    i = 0
    while (i < size1) :
        count1[ord(str1[i]) - ord('a')] += 1
        i += 1
        
    # count char frequency str2
    i = 0
    while (i < size2) :
        count2[ord(str2[i]) - ord('a')] += 1
        i += 1
            
    result = 0
    i = 0
    while (i < TotalABCLetters) :
        result += abs(count1[i] - count2[i])
        i += 1
    
    return result


str1 = "masterfx"
str2 = "ksampret"

print(CountCharactersNeedToBeRemovedForAnagram(str1, str2))



'''
run:
  
4
  
'''

 



answered Sep 28, 2022 by avibootz
edited Sep 29, 2022 by avibootz
0 votes
from collections import Counter

def CountCharactersNeedToBeRemovedForAnagram(str1, str2):
    return sum((Counter(str1) - Counter(str2) | Counter(str2) - Counter(str1)).values())

 
str1 = "masterfx"
str2 = "ksampret"
 
print(CountCharactersNeedToBeRemovedForAnagram(str1, str2))

 
 
 
'''
run:
   
4

'''

 



answered Sep 29, 2022 by avibootz
0 votes
from collections import Counter

def CountCharactersNeedToBeRemovedForAnagram(str1, str2):
    count_character = 0
    st = set() 
    for character in str1 + str2:
        if character not in st:
            st.add(character)
            count_character += abs(str1.count(character) - str2.count(character))
    return count_character

 
str1 = "masterfx"
str2 = "ksampret"
 
print(CountCharactersNeedToBeRemovedForAnagram(str1, str2))

 
 
 
'''
run:
   
4

'''

 



answered Sep 29, 2022 by avibootz
...