简体   繁体   English

如何在python 3中定义一个过程来调用函数

[英]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. 我编写了一个函数,该函数将两个字符串作为参数,并根据它们是否具有完全相同的字母返回true或false。 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. 现在,我需要定义一个名为test_anagram()的过程,该过程使用至少三种对与错情况来使用不同的字符串参数调用anagram函数。 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: 只需像定义其他函数一样定义它,然后在test_anagram传递字符串中将anagram函数作为参数调用即可:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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