调用不同的函数python

2024-09-27 21:27:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要调用我已经创建的各种不同的函数来实现下面的问题。我真的不确定该如何规划才能实现它。问题是。。在

在word list(str,str list)中查找两个单词的anagrams,其中输入参数应该 是一个字符串和一个字符串列表。输出应该是由两个字符串组成的所有字符串的列表 用空格隔开的单词,这样这两个单词都在str列表和组合中 这两个词中有一个str的变音

我期望的输出是:

wordlist = ('and','band','nor,'born')
find_two_word_anagrams_in_wordlist( "brandon", wordlist )
[’and born’, ’band nor’]

如何做到这一点:

  • 初始化一个list两个单词的anagrams到空列表[]。在
  • 调用find partial anagrams in word list获取所有 可以在单词列表中找到str的部分换位符。在
  • 然后,做一个循环,遍历所有这些部分变音图。为每一个 部分anagram part anag执行以下操作:
  • 从输入字符串str中删除部分anag的字母以获取 一个字符串,rem,它是去掉 偏字谜
  • 调用find anagrams in word list on rem(和输入单词列表)到 得到一个剩余字母的字谜列表
  • 对于剩余字母的每个换位符rem anag,形成字符串 part anag+“”+rem anag并将其添加到列表中的两个单词anagrams。在
  • 在这一点上,列表中的两个单词应该同时包含这两个单词 其中有一个单词,所以从函数中返回该列表。在

我已经创建的代码是:

^{pr2}$

任何一步一步的帮助或输入将不胜感激。在


Tags: 函数字符串in列表字母find单词list
2条回答

你有两个选择,你可以用两个不同的单词组合来查看字谜,或者你可以用两个组合来查看所有的字谜。在

你的选择权在这里,我已经实现了两者

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

这是一些测试

^{pr2}$

产生以下输出

[('and', 'born'), ('band', 'nor')]
[]
[('and', 'born'), ('band', 'nor')]
[('and', 'and')]

你写的

I need to call various different functions that i have already created in order to achieve the question below

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

请注意

  1. 您仍然需要按照您的规范编写内部函数
  2. 当你写一个返回的函数,例如,一个单词列表,你必须返回一个单词列表,特别是我的意思是,仅仅从函数中打印匹配项是不够的
  3. 要找到一个换位符,成语sorted(w1)==sorted(w2)就是你所需要的,但是找到一个部分换位符的故事要复杂得多。。。在
  4. 包含了你的一个函数的剩余部分。在
  5. 当您去掉注释(即您的逐字规范)时,您只有很少几行代码。在

后脚本

仔细看看丹尼尔对我之前的回答的评论,里面有很多。。。在

相关问题 更多 >

    热门问题