国产成人精品亚洲777人妖,欧美日韩精品一区视频,最新亚洲国产,国产乱码精品一区二区亚洲

您的位置:首頁技術(shù)文章
文章詳情頁

Python 找出英文單詞列表(list)中最長單詞鏈

瀏覽:19日期:2022-07-02 11:42:21

本文主要介紹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)!

標(biāo)簽: Python 編程
相關(guān)文章:
主站蜘蛛池模板: 巨野县| 沂水县| 梅河口市| 仙桃市| 抚远县| 宣化县| 东乡| 丰镇市| 南和县| 曲阜市| 兰西县| 霍林郭勒市| 北安市| 北流市| 东辽县| 伊川县| 醴陵市| 汉川市| 时尚| 奈曼旗| 昌邑市| 渭南市| 旬邑县| 卓尼县| 德江县| 罗定市| 东城区| 申扎县| 龙胜| 成武县| 德庆县| 郯城县| 烟台市| 奉贤区| 渝北区| 杭锦后旗| 施秉县| 苏尼特右旗| 同德县| 龙游县| 华蓥市|