Search code examples
pythonfunctionpython-3.3anagramprocedures

How to define a procedure to call a function in python 3


I have written a function that takes two strings as arguments and returns true or false on whether they have the exact same letters in them. This is my code for it:

def anagram(str1,str2):
    str1 = sorted(str1)
    str2 = sorted(str2)
    if str1 == str2:
        print("True")
    else:
        print("False")

I now need to define a procedure called test_anagram() that calls the anagram function with different string arguments, using at least three true and false cases. For each case the string and result should be printed out.

I'm not sure about how to achieve this, could anyone help me out?


Solution

  • Just define it like any other function and call the anagram function inside test_anagram pass strings as arguments:

    def test_anagram():
        strings = [("foo","bar"),("foo","oof"),("python","jython"),("tear","tare"),("foobar","bar"),("nod","don")] # create pairs of test strings
        for s1,s2 in strings: # ("foo","bar") -> s1 = "foo",s2 = "bar"...
            print(s1,s2) # print each string
            anagram(s1,s2) # call anagram, anagram("foo","bar") ...
    
    
    In [17]: test_anagram() # call test_anagram()
    ('foo', 'bar')
    False
    ('foo', 'oof')
    True
    ('python', 'jython')
    False
    ('tear', 'tare')
    True
    ('foobar', 'bar')
    False
    ('nod', 'don')
    True