Anagram Python 3

Whoo Cares picture Whoo Cares · Nov 13, 2013 · Viewed 10.5k times · Source

I'm trying to write a program that checks whether 2 inputs are anagrams. I feel like this should be relatively easy but I can't seem to figure it out. I'm supposed to define a function as:

def isAnagram(s1, s2):

so far, I have this:

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()

I guess I don't fully understand defining functions, so if you could please explain what's happening, that would be great!

Answer

abarnert picture abarnert · Nov 13, 2013

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.