Python 找出英文單詞列表(list)中最長(zhǎng)單詞鏈
本文主要介紹Python中單詞字符串的列表(list),找出列表中所有單詞中前一個(gè)單詞首字母和后一個(gè)單詞尾字母相同,組成最長(zhǎng)的單詞鏈方法代碼,并且每個(gè)單詞不能多次使用。
例如:
words = [’giraffe’, ’elephant’, ’ant’, ’tiger’, ’racoon’, ’cat’, ’hedgehog’, ’mouse’]
最長(zhǎng)的單詞鏈列表:
[’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)中最長(zhǎng)單詞鏈的文章就介紹到這了,更多相關(guān)Python 列表最長(zhǎng)單詞鏈內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. python如何實(shí)現(xiàn)word批量轉(zhuǎn)HTML2. 利用單元測(cè)試對(duì)PHP代碼進(jìn)行檢查3. Java8內(nèi)存模型PermGen Metaspace實(shí)例解析4. python excel和yaml文件的讀取封裝5. python3實(shí)現(xiàn)往mysql中插入datetime類(lèi)型的數(shù)據(jù)6. python爬蟲(chóng)實(shí)戰(zhàn)之制作屬于自己的一個(gè)IP代理模塊7. moment轉(zhuǎn)化時(shí)間戳出現(xiàn)Invalid Date的問(wèn)題及解決8. App啟動(dòng)優(yōu)化-Android性能優(yōu)化9. Django 權(quán)限管理(permissions)與用戶(hù)組(group)詳解10. Python編寫(xiě)單元測(cè)試代碼實(shí)例
