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']
工作原理類似于廣度優(yōu)先搜索,因為只要當前值之前沒有被調用,get_results函數就會繼續(xù)遍歷整個列表。函數已經查找過的值被添加到_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 排序最長英文單詞鏈內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
對python3 Serial 串口助手的接收讀取數據方法詳解
今天小編就為大家分享一篇對python3 Serial 串口助手的接收讀取數據方法詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-06-06Python創(chuàng)建exe運行器和截圖工具的示例詳解
本文我們將探討如何使用Python和wxPython創(chuàng)建一個強大而實用的桌面應用程序,可以遍歷指定文件夾中的所有EXE文件,感興趣的小伙伴可以了解一下2024-10-10