简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM