我需要调用我已经创建的各种不同的函数来实现下面的问题。我真的不确定如何编程以实现它。问题是......
在单词列表(str,str list)中找到两个单词anagrams,其中输入参数应该是 是一个字符串和一个字符串列表。输出应该是由两个组成的所有字符串的列表 由空格分隔的单词,这样这两个单词都在str列表和组合中 这两个词是str的字谜。
我期望的输出是:
wordlist = ('and','band','nor,'born')
find_two_word_anagrams_in_wordlist( "brandon", wordlist )
[’and born’, ’band nor’]
如何实现这一点:
我已创建的代码是:
def find_partial_anagrams_in_word_list(str1,str_list):
partial_anagrams = []
for word in str_list:
if (partial_anagram(word, str1)):
partial_anagrams.append(word)
print(partial_anagrams)
def remove_letters(str1,str2):
str2_list = list(str2)
for char in str2:
if char in str1:
str2_list.remove(char)
return "".join(str2_list)
def find_anagrams_in_word_list(str1,str_list):
anagrams = []
for word in str_list:
if (anagram(str1,word)):
anagrams.append(word)
print(word)
任何一步一步的帮助或输入都将不胜感激。
答案 0 :(得分:0)
你有两个选择,你可以看两个不同单词组合的字谜,或者你可以在两个组合中看到 all 中的字谜。
选择权在你手中,这里我实施了两个
from itertools import combinations, combinations_with_replacement
def ana2(s,wl):
rl = []
for w1, w2 in combinations(wl,2):
w = w1+w2
if len(w) != len(s): continue
if sorted(w) == sorted(s): rl.append((w1, w2)
return rl
def ana2wr(s,wl):
rl = []
for w1, w2 in combinations_with_replacement(wl,2):
w = w1+w2
if len(w) != len(s): continue
if sorted(w) == sorted(s): rl.append((w1, w2))
return rl
这里是一些测试
wl = ('and','band','nor','born')
s1 = 'brandon'
s2 = 'naddan
print ana2(s1,wl)
print ana2(s2,wl)
print ana2wr(s1,wl)
print ana2wr(s2,wl)
产生以下输出
[('and', 'born'), ('band', 'nor')]
[]
[('and', 'born'), ('band', 'nor')]
[('and', 'and')]
答案 1 :(得分:0)
你写了
我需要调用我已经创建的各种不同的函数 为了实现下面的问题
def find_2_word_anagram(word, wordlist)
# Initialise a list two word anagrams to the empty list, [].
analist = []
# Call find partial anagrams in word list to get a list of all the
# partial anagrams of str that can be found in the word list.
candidates = find_partial_anagrams_in_word_list(word,wordlist)
# Then, do a loop that runs over all these partial anagrams
for candidate in candidates:
# Remove the letters of part anag from the input string, str, to
# get a string, rem that is the remaining letters after taking
# away the partial anagram
remaining = remove_letter(candidate,words)
# Call find anagrams in word list on rem (and the input word list)
# to get a list of anagrams of the remaining letters;
matches = find_anagrams_in_word_list(remaining, wordlist)
for other in matches:
analist.append(" ".join(candidate,other))
return analist
请注意
sorted(w1)==sorted(w2)
就是你所需要的,但找到部分字谜的故事更复杂...... 彻底了解丹尼尔对我之前回答的评论,其中有很多内容......