失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > python中排序英文单词怎么写_Python 排序最长英文单词链(列表中前一个单词末字母是下

python中排序英文单词怎么写_Python 排序最长英文单词链(列表中前一个单词末字母是下

时间:2021-03-15 19:28:13

相关推荐

python中排序英文单词怎么写_Python 排序最长英文单词链(列表中前一个单词末字母是下

本文主要介绍排序最长的单词链的方法,列表中每个元素相当于一个单词,要实现列表中前一个单词末字母是下一个单词的首字母,并且这个链是最长的。

使用递归实现

words = ['giraffe', 'elephant', 'ant', 'tiger', 'racoon', 'cat', 'hedgehog', 'mouse']

def get_results(_start, _current, _seen):

if all(c in _seen for c in words if c[0] == _start[-1]):

yield _current

else:

for i in words:

if i[0] == _start[-1]:

yield from get_results(i, _current+[i], _seen+[i])

new_d = [list(get_results(i, [i], []))[0] for i in words]

final_d = max([i for i in new_d if len(i) == len(set(i))], key=len)

输出:

['hedgehog', 'giraffe', 'elephant', 'tiger', 'racoon']

工作原理类似于广度优先搜索,因为只要当前值之前没有被调用,get_results函数就会继续遍历整个列表。函数已经查找过的值被添加到_seen列表中,最终停止递归调用流。这个解决方案也会忽略重复的结果,

words = ['giraffe', 'elephant', 'ant', 'ning', 'tiger', 'racoon', 'cat', 'hedgehog', 'mouse',]

new_d = [list(get_results(i, [i], []))[0] for i in words]

final_d = max([i for i in new_d if len(i) == len(set(i))], key=len)

输出:

['ant', 'tiger', 'racoon', 'ning', 'giraffe', 'elephant']

python中排序英文单词怎么写_Python 排序最长英文单词链(列表中前一个单词末字母是下一个单词的首字母)...

如果觉得《python中排序英文单词怎么写_Python 排序最长英文单词链(列表中前一个单词末字母是下》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。