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 排序最长英文单词链内容请搜索好吧啦网以前的文章或继续浏览下面的相关文章希望大家以后多多支持好吧啦网!
相关文章:
1. 解决Ajax方式上传文件报错"Uncaught TypeError: Illegal invocation"2. bootstrap select2 动态从后台Ajax动态获取数据的代码3. 利用FastReport传递图片参数在报表上展示签名信息的实现方法4. ASP.NET MVC获取多级类别组合下的产品5. jsp request.getParameter() 和request.getAttribute()方法区别详解6. 使用游标进行PHP SQLSRV查询的方法与注意事项7. PHP设计模式中工厂模式深入详解8. JSP数据交互实现过程解析9. 一篇文章带你了解JavaScript-对象10. Ajax对xml信息的接收和处理操作实例分析
