【问题标题】:Function which find longest circle sequence from set of words从一组单词中找到最长圆序列的函数
【发布时间】:2021-12-27 21:05:07
【问题描述】:

我的问题很简单。

我有这个代码

def get_neighbors(word, choices):
    return set(x for x in choices if x[0] == word[-1])


def longest_path_from(word, choices):
    choices = choices - {word}
    neighbors = get_neighbors(word, choices)

    if neighbors:
        paths = (longest_path_from(w, choices) for w in neighbors)
        max_path = max(paths, key=len)
    else:
        max_path = []

    return [word] + max_path


def longest_path(choices):
    return max((longest_path_from(w, choices) for w in choices), key=len)

从单词集中找到最长的序列,其中第一个单词的最后一个字母等于第二个单词的第一个字母

我想调整这段代码来找到最长的循环序列。

举个例子。

  • longest_path({'ca', 'abc', 'cd', 'da'}) 返回 ['ca', 'abc', 'cd', 'da'] 这是正确的,但我希望它是 ["abc","cd","da"] 所以还有一个条件,那就是最后一个单词的最后一个字符匹配第一个单词的第一个字符。

我好像找不到放哪里了。

感谢您的帮助。

【问题讨论】:

  • longest_path_from 返回所有可能序列的集合。您所要做的就是拒绝那些不圈出的人。

标签: python string recursion


【解决方案1】:

根据我的评论,longest_path_from 会将它找到的所有序列返回给您。只需遍历那些并丢弃那些不是循环的。

def get_neighbors(word, choices):
    return set(x for x in choices if x[0] == word[-1])

def longest_path_from(word, choices):
    choices = choices - {word}
    neighbors = get_neighbors(word, choices)

    if neighbors:
        paths = (longest_path_from(w, choices) for w in neighbors)
        max_path = max(paths, key=len)
    else:
        max_path = []

    return [word] + max_path


def longest_path(choices):
    newlist = []
    for s in list(longest_path_from(w, choices) for w in choices):
        if s[0][0] == s[-1][-1]:
            newlist.append( s )
    return max(len(s) for s in newlist)

print(longest_path({'ca','abc','cd','da'}))

longest_path 可以变成单行,但这是病态的。 ;)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-07
    • 1970-01-01
    • 1970-01-01
    • 2022-12-01
    • 2021-10-17
    • 1970-01-01
    相关资源
    最近更新 更多