pythonanagram

Anagram Python 3


How can I write a function that checks whether 2 inputs are anagrams?

word1 = input("Enter a string: ")
word2 = input("Enter a second string: ")

def isAnagram(s1, s2):
    s1 = word1.sort()
    s2 = word2.sort()
    if s1 == s2:
       print("This is an anagram")
    else:
       print("This is not an anagram)
isAnagram()

Solution

  • You've defined the function almost correctly, but there are a few problems.

    First you're asking for s1 and s2 as parameters. That's good. Now use those values, not the globals word1 and word2.

    Second, if those values are strings, you can't call sort on them, because strings don't have a sort method. But you can call the sorted function on any sequence, even strings.

    Third, there's a simple typo, a missing " on the second print.

    It might be better to return a True or False value, and put the print outside the function, but let's leave that for now.

    Putting that together, here's a working function:

    def isAnagram(s1, s2):
        s1 = sorted(s1)
        s2 = sorted(s2)
        if s1 == s2:
           print("This is an anagram")
        else:
           print("This is not an anagram")
    

    But now, you have to call the function properly, too. You've defined the function to take two parameters, s1 and s2. That means you need to call the function with two arguments.

    So, where do you get those arguments? Well, you've already got those variables word1 and word2 sitting around, and they seem like exactly what you want.

    So, change the last line to:

    isAnagram(word1, word2)
    

    And you're done.