Python 找出英文單詞列表(list)中最長單詞鏈
本文主要介紹Python中單詞字符串的列表(list),找出列表中所有單詞中前一個(gè)單詞首字母和后一個(gè)單詞尾字母相同,組成最長的單詞鏈方法代碼,并且每個(gè)單詞不能多次使用。
例如:
words = [’giraffe’, ’elephant’, ’ant’, ’tiger’, ’racoon’, ’cat’, ’hedgehog’, ’mouse’]
最長的單詞鏈列表:
[’hedgehog’, ’giraffe’, ’elephant’, ’tiger’, ’racoon’]1、用遞歸方法查找
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)
輸出結(jié)果:
[’hedgehog’, ’giraffe’, ’elephant’, ’tiger’, ’racoon’]
2、使用networkx查找import networkx as nximport matplotlib.pyplot as pltwords = [’giraffe’, ’elephant’, ’ant’, ’tiger’, ’racoon’, ’cat’, ’hedgehog’, ’mouse’]G = nx.DiGraph()G.add_nodes_from(words)for word1 in words: for word2 in words: if word1 != word2 and word1[-1] == word2[0]: G.add_edge(word1, word2)nx.draw_networkx(G)plt.show()print(nx.algorithms.dag.dag_longest_path(G))
到此這篇關(guān)于Python 找出英文單詞列表(list)中最長單詞鏈的文章就介紹到這了,更多相關(guān)Python 列表最長單詞鏈內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. python b站視頻下載的五種版本2. 如何通過vscode運(yùn)行調(diào)試javascript代碼3. 半小時(shí)實(shí)現(xiàn)Java手?jǐn)]網(wǎng)絡(luò)爬蟲框架(附完整源碼)4. 測試模式 - XSL教程 - 55. 教你JS更簡單的獲取表單中數(shù)據(jù)(formdata)6. JAVA抽象類及接口使用方法解析7. python如何寫個(gè)俄羅斯方塊8. 《CSS3實(shí)戰(zhàn)》筆記--漸變設(shè)計(jì)(一)9. Python結(jié)合百度語音識(shí)別實(shí)現(xiàn)實(shí)時(shí)翻譯軟件的實(shí)現(xiàn)10. JavaScript設(shè)計(jì)模式之策略模式實(shí)現(xiàn)原理詳解
![半小時(shí)實(shí)現(xiàn)Java手?jǐn)]網(wǎng)絡(luò)爬蟲框架(附完整源碼)](http://www.intensediesel.com/attached/image/7.jpg)