Python 找出英文单词列表(list)中最长单词链
本文主要介绍Python中单词字符串的列表(list),找出列表中所有单词中前一个单词首字母和后一个单词尾字母相同,组成最长的单词链方法代码,并且每个单词不能多次使用。
例如:
words=['giraffe','elephant','ant','tiger','racoon','cat','hedgehog','mouse']
最长的单词链列表:
['hedgehog','giraffe','elephant','tiger','racoon']
1、用递归方法查找
words=['giraffe','elephant','ant','tiger','racoon','cat','hedgehog','mouse'] defget_results(_start,_current,_seen): ifall(cin_seenforcinwordsifc[0]==_start[-1]): yield_current else: foriinwords: ifi[0]==_start[-1]: yieldfromget_results(i,_current+[i],_seen+[i]) new_d=[list(get_results(i,[i],[]))[0]foriinwords] final_d=max([iforiinnew_diflen(i)==len(set(i))],key=len)
输出结果:
['hedgehog','giraffe','elephant','tiger','racoon']
2、使用networkx查找
importnetworkxasnx importmatplotlib.pyplotasplt words=['giraffe','elephant','ant','tiger','racoon','cat', 'hedgehog','mouse'] G=nx.DiGraph() G.add_nodes_from(words) forword1inwords: forword2inwords: ifword1!=word2andword1[-1]==word2[0]: G.add_edge(word1,word2) nx.draw_networkx(G) plt.show() print(nx.algorithms.dag.dag_longest_path(G))
到此这篇关于Python找出英文单词列表(list)中最长单词链的文章就介绍到这了,更多相关Python列表最长单词链内容请搜索毛票票以前的文章或继续浏览下面的相关文章希望大家以后多多支持毛票票!
热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下