George Orchard George Orchard - 1 month ago 8
Python Question

Basic Python: comparing lists

This is all I have so far:

def anagram(str1, str2):

print("String 1 : %s" %str1)
print("String 2 : %s" %str2)
s1 = sorted(str1.lower())
s2 = sorted(str2.lower())

if s1 == s2:
print("This is an anagram")
return True

def test_anagram():

print( "\n** Testing example anagrams **\n")

tests = [["dog", "cat"]]

num_anagrams = 0

for test in tests:
answer = anagram(test[0] , test[1])
print("For inputs " + test[0] + " and " + test[1] + " answer is: ", answer, end ="")
if answer == test[0]:
print("This test is correct")
num_anagrams += 1


I don't think this is close to right. I want it to compare the actual result to what the function previously gives out as a result, then output whether the result was the same, being 'correct' or not 'incorrect' then output how many tests worked correctly against the function. I can't get my head around the if statement.

Thanks for the help!

Answer

Fixed your code based on what I thought you wanted to do with some comments on what was changed and why:

def anagrams(str1, str2):
    print("String 1 : %s" %str1) #you wanted to print it right this is how you can format the string with variables
    print("String 2 : %s" %str2) #you wanted to print it right this is how you can format the string with variables
    s1 = sorted(str1.lower()) #lower function call to remove the capital letters since it matters
    s2 = sorted(str2.lower()) #lower function call to remove the capital letters since it matters

    if s1 == s2:
        print("This is an anagram") # you don't call a bool value with parameter. You use print functions instead and then return True
        return True #you wanted to return True here right? 



anagrams("Cat", "Tac") # no need to assign variables to match parameter names

This prints out:

String 1 : Cat
String 2 : Tac
This is an anagram

I think you were mistaking on how to print things out with variable assignment to the string, I vaguely remember a language that had that had a similar syntax with what you were doing.

You error is basically trying to call a str object like a function. Since you took other programming language, I think you should know what's wrong with that statement

Edited:

def anagram(str1, str2):

    print("String 1 : %s" %str1) 
    print("String 2 : %s" %str2)
    s1 = sorted(str1.lower()) 
    s2 = sorted(str2.lower())

    if s1 == s2:
        print("This is an anagram") 
        return True

def test_anagram():

    print( "\n** Testing example anagrams **\n")

    tests = [["dog", "cat"],["tac","cat"],["dog","god"]]

    num_anagrams = 0

    for test in tests:
        answer = anagram(test[0] , test[1])
        print("For inputs " + test[0] + " and " + test[1] + " answer is: " + str(answer))
        if answer:
            print("This test is correct")
            num_anagrams += 1
    print(num_anagrams)

test_anagram()
Comments