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列表最长单词链内容请搜索毛票票以前的文章或继续浏览下面的相关文章希望大家以后多多支持毛票票!
热门推荐
10 儿子立冬祝福语简短独特
11 对当兵的祝福语简短
12 侄儿高考试祝福语简短
13 伴郎红包祝福语朋友简短
14 媳妇生日简短祝福语朋友
15 公司年会祝福语简短最好
16 元旦感恩祝福语简短大全
17 红包祝福语简短10字
18 周六早晨祝福语简短