How to check if two strings are anagram (same letters different words) in Python

3 Answers

0 votes
s1 = "python"
s2 = "thonpy"

if sorted(s1) == sorted(s2):  
    print("Anagram") 
else:  
    print("Not Anagram") 
     
 

'''
run:
 
Anagram
 
'''

 



answered Jan 28, 2019 by avibootz
edited Nov 10, 2021 by avibootz
0 votes
def isAnagram(s1, s2):  
    lens1 = len(s1)  
    lens2 = len(s2)  
  
    if lens1 != lens2:  
        return 0
  
    s1 = sorted(s1) 
    s2 = sorted(s2) 
  
    if s1 != s2:  
        return 0
  
    return 1
  
  
s1 = "python"
s2 = "thonpy"
if isAnagram(s1, s2):  
    print("Anagram") 
else:  
    print("Not Anagram") 
    


'''
run:

Anagram

'''

 



answered Jan 28, 2019 by avibootz
edited Nov 10, 2021 by avibootz
0 votes
from collections import Counter 

def is_anagram(s1, s2): 
     return Counter(s1) == Counter(s2) 
     
print(is_anagram('python', 'thonpy')) 
print(is_anagram('php', 'hpp'))     
print(is_anagram('c++', 'cpp'))  



'''
run

True
True
False

'''

 



answered Apr 9, 2019 by avibootz
...