[英]defining a function which calls another function for a variety of strings python
I have a code which finds anagrams of a string in a dictionary file. 我有一个代码,可在字典文件中找到字符串的字谜。 I want to create a function which tests a variety of strings called test_find_anagrams().
我想创建一个测试各种字符串的函数,称为test_find_anagrams()。 It should test at least 6 different strings.
它应该测试至少6个不同的字符串。
This is the code i have which tests a single string in a file. 这是我测试文件中单个字符串的代码。
def anagram(str1,str2):
str1 = sorted(str1)
str2 = sorted(str2)
return str1 == str2
def get_dictionary_word_list():
with open('dictionarys.txt') as f:
return f.read().split()
def find_anagrams(str):
return [word for word in get_dictionary_word_list() if anagram(word,str)]
So far i have this code to test different strings, It works on the first string in the list but doesnt return anything for any string after. 到目前为止,我有这段代码可以测试不同的字符串,它适用于列表中的第一个字符串,但之后的任何字符串均不返回任何内容。 What else do i need to put in the code for it to work?
我还需要在代码中加上什么才能使其正常工作?
def test_find_anagrams():
stringlist = [('aces'), ('sidebar'), ('adverb'), ('fuels'), ('hardset'), ('praised')]
for str1 in stringlist:
return [word for word in get_dictionary_word_list() if anagram(word,str1)]
It only "works on the first string in the list" because you return from inside the loop. 它仅“在列表中的第一个字符串上起作用”,因为您是从循环内部返回的。 Keep track of your result outside of the loop.
在循环之外跟踪结果。
def test_find_anagrams():
stringlist = [('aces'), ('sidebar'), ('adverb'), ('fuels'), ('hardset'), ('praised')]
result = []
for str1 in stringlist:
result.extend(word for word in get_dictionary_word_list() if anagram(word,str1))
return result
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.