Home > Mobile >  define anagram Python
define anagram Python

Time:10-31

Could anyone help? Need to define words on being Anagrams. But exactly the same words are not anagram. For example: cat - kitten The words aren't anagrams; cat - act The words are anagrams; cat - cat should be The same words. What should l do in this code to include The same words:

s1 = input("Enter first word:")
s2 = input("Enter second word:")
a = sorted(s for s in s1.lower() if s.isalpha())
b = sorted(s for s in s2.lower() if s.isalpha())
if sorted(a) == sorted(b):
    print("The words are anagrams.")
else:
    print("The words aren't anagrams.")

CodePudding user response:

I would do a check after gathering the input.

    s1 = input("Enter first word:").lower().lower()
    s2 = input("Enter second word:")
    if s1 != s2:
        a = sorted(s for s in s1 if s.isalpha())
        b = sorted(s for s in s2 if s.isalpha())
        if sorted(a) == sorted(b):
            print("The words are anagrams.")
        else:
            print("The words aren't anagrams.")
    else:
        print("The words are anagrams.")
    ```
  • Related