>> find_sub_anagram_in_wordlist('apple', ['ppl','al','app','apple'])
['ppl']
为什么循环不添加其他子字谜?你知道吗
这是我的密码:
anagramList = []
def find_sub_anagram_in_wordlist(str, str_list):
global anagramList
anagramList.clear()
list1 = list(str)
list1.sort()
for word in str_list:
shouldAdd = True
listi = list(word)
listi.sort()
for j in listi:
if j in list1:
list1.remove(j)
else:
shouldAdd = False
if shouldAdd == True:
anagramList.append(word)
return anagramList
这条线:
是你的问题。想想
for word in str_list
的第一次迭代,其中word == 'ppl
请牢记以下代码:
这将留给您
list1 == ['a','e']
。对word
的下一次迭代将提供word == 'al'
。如果我们再看一遍上面的代码,您将看到,因为在list1
,shouldAdd == False
中不再有'l'
。而且,因为a
在里面,所以现在不是了。你可以看到这是怎么回事。你知道吗使用您的代码,您可以通过将
list1 = list(str)
移动到for word in str_list:
循环的内部来解决这个问题,这样每次它都会重新初始化列表。我将尝试找到一个更为python的方法来完成这个函数,并在我可以的时候发布它。你知道吗编辑:
以下是我的方法:
我认为这有助于简化你的工作。特别是,从功能上把子项的测试与筛选候选项的过程分开。这就是我的方法:
输出为:
请注意,
'aapl'
不是也不应该包含在输出中。你知道吗相关问题 更多 >
编程相关推荐